﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
using System.Reflection;


namespace rowa.Drive
{
    /// <summary>
    /// Erstellung und Löschung nicht persistenter virtueller Laufwerke.
    /// Das Laufwerk muss nach jedem Neustart des Systems wiederhergestellt werden.
    /// Wird nicht unter dem Registryschlüssel angezeigt : HKLM\System\MountedDevices.
    /// 
    /// VirtualDrive - © Konstantin Gross
    /// </summary>
    public class VirtualDrive
    {
        #region Win32
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern bool DefineDosDevice(
            int dwFlags,
            string lpDeviceName,
            string lpTargetPath
            );

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern int GetDriveType(
            string lpRootPathName
            );

        private const int DDD_RAW_TARGET_PATH = 0x00000001;
        private const int DDD_REMOVE_DEFINITION = 0x00000002;
        private const int DDD_EXACT_MATCH_ON_REMOVE = 0x00000004;

        private const int DRIVE_UNKNOWN = 0;
        private const int DRIVE_NO_ROOT_DIR = 1;
        private const int DRIVE_FIXED = 3;
        #endregion // Win32

        #region Öffentliche Methoden

        #region Erstellen
        /// <summary>
        /// Erstellung eines nicht persistenten Laufwerks.
        /// </summary>
        /// <param name="driveChar">Laufwerksbuchstabe.</param>
        /// <param name="path">Pfad zu dem zu verknüpfenden Ordner.</param>
        /// <returns>True/False beim Versuch das Laufwerk zu erstellen</returns>
        public static bool Create(char driveChar, string path)
        {
            return DDDOperation(driveChar, path, true);
        }
        #endregion // Erstellen

        #region Löschen
        /// <summary>
        /// Löschung eines nicht persistenten Laufwerks.
        /// </summary>
        /// <param name="driveChar">Laufwerksbuchstabe.</param>
        /// <param name="path">Pfad zu dem zu verknüpfenden Ordner.</param>
        /// <returns>True/False beim Versuch das Laufwerk zu löschen</returns>
        public static bool Delete(char driveChar, string path)
        {
            return DDDOperation(driveChar, path, false);
        }
        #endregion // Löschen

        #endregion // Öffentliche Methoden

        #region Private Methoden

        #region DDDOperationen
        private static bool DDDOperation(char driveChar, string path, bool create)
        {
            //Gültiges Verzeichnis?
            if (!Directory.Exists(path))
                return false;

            string drive = string.Format("{0}:", driveChar.ToString().ToUpper());

            //Existiert das Volumen?
            int type = GetDriveType(string.Format("{0}{1}", drive, Path.DirectorySeparatorChar));

            //Hinweiß: Ein erstelltes virtuelles Laufwerk ist vom Typ DRIVE_FIXED
            if ((create && type != DRIVE_UNKNOWN && type != DRIVE_NO_ROOT_DIR) ||
                (!create && type != DRIVE_FIXED))
                return false;

            int flags = DDD_RAW_TARGET_PATH;

            if (!create) flags |= (DDD_REMOVE_DEFINITION | DDD_EXACT_MATCH_ON_REMOVE);
            return DefineDosDevice(
                flags,
                drive,
                string.Format("{0}??{0}{1}", Path.DirectorySeparatorChar, path)
                );
        }
        #endregion // DDDOperationen

        #endregion // Private Methoden
    }
}

namespace rowa.debug
{
    public static class tools
    {
        public static bool IsDebugModus()
        {
        	return System.Diagnostics.Debugger.IsAttached;
        }
    }
}

namespace rowa.financial
{
    public class stock
    {
        private static System.Data.DataSet getStockQuotadataset(string content)
        {
            try
            {
                System.Data.DataTable dt = new System.Data.DataTable();
                dt.TableName = "Stockquotes";
                System.Data.DataColumn dc = null;

                char[] delimiters = new char[] { ',' };
                string[] words = content.Split(delimiters);

                dc = new System.Data.DataColumn();
                dc.ColumnName = "Symbol";
                dt.Columns.Add(dc);

                dc = new System.Data.DataColumn();
                dc.ColumnName = "Value";
                dt.Columns.Add(dc);

                dc = new System.Data.DataColumn();
                dc.ColumnName = "Date";
                dt.Columns.Add(dc);

                dc = new System.Data.DataColumn();
                dc.ColumnName = "Time";
                dt.Columns.Add(dc);

                dc = new System.Data.DataColumn();
                dc.ColumnName = "Performance";
                dt.Columns.Add(dc);

                dc = new System.Data.DataColumn();
                dc.ColumnName = "Open";
                dt.Columns.Add(dc);

                dc = new System.Data.DataColumn();
                dc.ColumnName = "DaysMax";
                dt.Columns.Add(dc);

                dc = new System.Data.DataColumn();
                dc.ColumnName = "DaysMin";
                dt.Columns.Add(dc);

                dc = new System.Data.DataColumn();
                dc.ColumnName = "Volume";
                dt.Columns.Add(dc);

                System.Data.DataRow row = dt.NewRow();

                for (int w = 0; w < words.Length; w++)
                {
                    row[w] = words[w].Replace("\"", "");
                }
                dt.Rows.Add(row);
                System.Data.DataSet ds = new System.Data.DataSet("financial");
                ds.Tables.Add(dt);
                return ds;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public static System.Data.DataSet quotes(string symbol, int timeout)
        {
                return getStockQuotadataset(rowa.web.Content.readcontent("http://download.finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=sl1d1t1c1ohgv&e=.xml"));
        }
        public static System.Data.DataSet quotes(string symbol, int timeout, string proxy)
        {
            return getStockQuotadataset(rowa.web.Content.readcontent("http://download.finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=sl1d1t1c1ohgv&e=.xml", proxy));
        }
    }

}
namespace rowa.messaging
{
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
        /// <summary>
        /// Syslogger Klasse zum versenden von Syslogmeldungen
        /// </summary>
      public class Syslog
      {
        private UdpClient syslogClient = new UdpClient();

        /// <summary>
        /// Facility für den Syslogger
        /// </summary>
        public enum Facility : int
        {
          System0 = 10,
          System1 = 11,
          System2 = 12,
          System3 = 13,
          System4 = 14,
            System5 = 15,
            local0 = 16,
            local1 = 17,
            local2 = 18,
            local3 = 19,
            local4 = 20,
            local5 = 21,
            local6 = 22,
            local7 = 23

        }

        /// <summary>
        /// Prio für den Syslogger
        /// </summary>
        public enum Prio : int
        {
          Emergency = 0,
          Alert = 1,
          Critical = 2,
          ErrorMessage = 3,
          Warning = 4,
          Notice = 5,
          Informational = 6,
          Debug = 7
        }

        /// <summary>
        /// versenden eine Sysloggmessage
        /// </summary>
        /// <param name="server"></param>
        /// <param name="message"></param>
        /// <param name="Facility"></param>
        /// <param name="prio"></param>
        public void send(string server, string message, int Facility, int prio)
        {
            try
            {
                Facility = Facility * 8;
                UdpClient syslogClient = new UdpClient();
                syslogClient = new UdpClient();
                string syslogIdent;
                syslogClient.Connect(server, 514);
                syslogIdent = "syslogger";
                byte[] logdata = new byte[1024];
                logdata = Encoding.ASCII.GetBytes("<" + Facility + prio + ">" + syslogIdent + ": " + message);
                syslogClient.Send(logdata, logdata.Length);
                syslogClient.Close();
            }
            catch
            {

            }


        }

        /// <summary>
        /// versenden eine Sysloggmessage
        /// </summary>
        /// <param name="server"></param>
        /// <param name="message"></param>
        public void send(string server, string message)
        {
            try
            {
                UdpClient syslogClient = new UdpClient();
                syslogClient = new UdpClient();
                string syslogIdent;
                syslogClient.Connect(server, 514);
                syslogIdent = "syslogger";
                byte[] logdata = new byte[1024];
                logdata = Encoding.ASCII.GetBytes("<" + Facility.System0 + Prio.ErrorMessage + ">" + syslogIdent + ": " + message);
                syslogClient.Send(logdata, logdata.Length);
                syslogClient.Close();
            }
            catch
            {

            }

    
        }

        public void websend(string message)
        {
            try
            {
                send(System.Web.Configuration.WebConfigurationManager.AppSettings["syslogclient"], message);
            }
            catch
            {

            }
        }


      }

      public class error
      {
          public static void errorlog(string filename, string text, Exception ex)
          {
              try
              {
                  StreamWriter writer;

                  // open file
                  if (!File.Exists(filename))
                  {
                      writer = new StreamWriter(filename);
                  }
                  else
                  {
                      writer = new StreamWriter(filename, true);
                  }

                  // write message line
                  writer.WriteLine(text);
                  writer.WriteLine(ex.ToString());
                  writer.Close();
              }
              catch
              {

              }

          }
      }


    public class eMail
    {
             public static bool sendmail(string from, string to, string subject, string text, string mailserver)
        {
            try
            {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to, subject, text);
                System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient(mailserver);
                smtpclient.Send(message);
                return true;
            }
            catch
            {
                return false;
            }

        }

             public static bool sendmail(string from, string to, Exception ex, string mailserver)
             {
                 try
                 {
                     sendmail(from, to, "Application Error PC: " + System.Environment.MachineName, ex.ToString() + "\n" + System.AppDomain.CurrentDomain, mailserver);
                     return true;
                 }
                 catch
                 {
                     return false;
                 }

             }



    }


}
namespace rowa.data
{
    using System.Data.SqlClient;
    using System.Data;
    using System.Xml;
    using System.Collections;
    using System.IO;
    public class helpers
    {

        public static byte[] StringToByteArray(string str)
        {
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            return enc.GetBytes(str);
        }

        public static string ByteArrayToString(byte[] arr)
        {
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            return enc.GetString(arr);
        }


        public static DataSet ConvertDataReadertoDataSet(IDataReader reader)
        {
            DataSet ds = new DataSet();
            DataTable dataTable = new DataTable();

            DataTable schemaTable = reader.GetSchemaTable();

            DataRow row;
            string columnName;
            DataColumn column;

            int count = schemaTable.Rows.Count;

            for (int i = 0; i < count; i++)
            {
                row = schemaTable.Rows[i];
                columnName = (string)row["ColumnName"];
                column = new DataColumn(columnName, (Type)row["DataType"]);
                dataTable.Columns.Add(column);
            }
            ds.Tables.Add(dataTable);

            object[] values = new object[count];

            try
            {
                dataTable.BeginLoadData();
                while (reader.Read())
                {
                    reader.GetValues(values);
                    dataTable.LoadDataRow(values, true);
                }

            }
            finally
            {
                dataTable.EndLoadData();
                reader.Close();
            }

            return ds;
        } 
    }

    /// <summary>
    /// Only SQL Server Connections!
    /// </summary>
    public class XMLDocuments
    {


        public static XmlDocument getXML(ref SqlParameter[] para, string spName, bool BackreplaceEntity, ref SqlConnection conn)
        {
            XmlReader xr = null;
            SqlCommand sqlCmd = new SqlCommand(spName, conn);
            sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
            sqlCmd.CommandTimeout = 15000;
            sqlCmd.Parameters.AddRange(para);

            System.DateTime startTime = System.DateTime.Now;
            while (rowa.Date.DateAndTime.DateDiff(rowa.Date.DateInterval.Second, startTime, System.DateTime.Now) < 20)
            {
                try
                {
                    xr = sqlCmd.ExecuteXmlReader();
                    xr.Read();
                    XmlDocument xd = new XmlDocument();

                    if (BackreplaceEntity == true)
                    {
                        string ReadOuterXml = xr.ReadOuterXml();
                        ReadOuterXml = ReadOuterXml.Replace("&amp;amp;", "&amp;");
                        xd.LoadXml(ReadOuterXml);
                    }
                    else
                    {
                        xd.LoadXml(xr.ReadOuterXml());
                    }
                    
                    
                    
                    return xd;
                }
                catch (SqlException ex)
                {
                    if (ex.Number != 1205)
                    {
                        throw ex;
                    }
                    else
                    {
                        rowa.messaging.Syslog sy1 = new messaging.Syslog();
                        sy1.websend("Deadlock Exception");
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");
        }


        public static XmlDocument getXML(ref SqlParameter[] para, string spName, ref SqlConnection conn)
        {
            return getXML(ref para, spName, false, ref conn);
        }

        public XmlDocument getXML(ref SqlParameter[] para, string spName, ref SqlParameter returnpara, ref SqlConnection conn)
        {
            return getXML(ref para, spName, ref returnpara, false, ref conn);
        }

        public XmlDocument getXML(ref SqlParameter[] para, string spName, ref SqlParameter returnpara, bool BackreplaceEntity, ref SqlConnection conn)
        {
            XmlReader xr = null;
            SqlCommand sqlCmd = new SqlCommand(spName, conn);
            sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
            sqlCmd.CommandTimeout = 15000;
            sqlCmd.Parameters.AddRange(para);
            sqlCmd.Parameters.Add(returnpara).Direction = ParameterDirection.ReturnValue;

            System.DateTime startTime = System.DateTime.Now;
            while (rowa.Date.DateAndTime.DateDiff(rowa.Date.DateInterval.Second, startTime, System.DateTime.Now) < 20)
            {
                try
                {

                    xr = sqlCmd.ExecuteXmlReader();
                    xr.Read();
                    XmlDocument xd = new XmlDocument();

                    if (BackreplaceEntity == true)
                    {
                        string ReadOuterXml = xr.ReadOuterXml();
                        ReadOuterXml = ReadOuterXml.Replace("&amp;amp;", "&amp;");
                        xd.LoadXml(ReadOuterXml);
                    }
                    else
                    {
                        xd.LoadXml(xr.ReadOuterXml());
                    }
                    
                    return xd;
                }
                catch (SqlException ex)
                {
                    if (ex.Number != 1205)
                    {
                        throw ex;
                    }
                    else
                    {
                        rowa.messaging.Syslog sy1 = new messaging.Syslog();
                        sy1.websend("Deadlock Exception");
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");

        }



        public static XmlDocument getXML(string sql, ref SqlConnection conn)
        {

            if (sql.ToLower().Contains("for xml auto") == false)
            {
                sql = sql + "  FOR XML AUTO";
            }
            XmlReader xr = null;
            SqlCommand myCommand = new SqlCommand(sql, conn);
            myCommand.CommandTimeout = 15000;
            System.DateTime startTime = System.DateTime.Now;
            while (rowa.Date.DateAndTime.DateDiff(rowa.Date.DateInterval.Second, startTime, System.DateTime.Now) < 20)
            {
                try
                {
                    xr = myCommand.ExecuteXmlReader();
                    xr.Read();
                    XmlDocument xd = new XmlDocument();
                    xd.LoadXml(xr.ReadOuterXml());

                    myCommand.Dispose();

                    return xd;
                }
                catch (SqlException ex)
                {
                    if (ex.Number != 1205)
                    {
                        throw ex;
                    }
                    else
                    {
                        rowa.messaging.Syslog sy1 = new messaging.Syslog();
                        sy1.websend("Deadlock Exception");
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");
        }

    

    }


    public class XMLReaders
    {
        public XmlReader getXML(ref SqlParameter[] para, string spName, ref SqlConnection conn)
        {
            System.DateTime startTime = System.DateTime.Now;
            XmlReader xr = null;
            SqlCommand sqlCmd = new SqlCommand(spName, conn);
            sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
            sqlCmd.CommandTimeout = 15000;
            sqlCmd.Parameters.AddRange(para);

            while (rowa.Date.DateAndTime.DateDiff(rowa.Date.DateInterval.Second, startTime, System.DateTime.Now) < 20)
            {
                try
                {
                    xr = sqlCmd.ExecuteXmlReader();
                    xr.Read();
                    return xr;
                }
                catch (SqlException ex)
                {
                    if (ex.Number != 1205)
                    {
                        throw ex;
                    }
                    else
                    {
                        rowa.messaging.Syslog sy1 = new messaging.Syslog();
                        sy1.websend("Deadlock Exception");
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");

        }
        public XmlReader getXML(string sql, ref SqlConnection conn)
        {
            if (sql.ToLower().Contains("for xml auto") == false)
            {
                sql = sql + "  FOR XML AUTO";
            }
            XmlReader xr = null;
            SqlCommand myCommand = new SqlCommand(sql, conn);
            myCommand.CommandTimeout = 15000;
            System.DateTime startTime = System.DateTime.Now;
            while (rowa.Date.DateAndTime.DateDiff(rowa.Date.DateInterval.Second, startTime, System.DateTime.Now) < 20)
            {
                try
                {
                    xr = myCommand.ExecuteXmlReader();
                    //xr.Read();
                    myCommand.Dispose();
                    return xr;
                }
                catch (SqlException ex)
                {
                    if (ex.Number != 1205)
                    {
                        throw ex;
                    }
                    else
                    {
                        rowa.messaging.Syslog sy1 = new messaging.Syslog();
                        sy1.websend("Deadlock Exception");
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");

        }
    }

    public class executer
    {
        public static bool executeNonQuery(string sql, ref SqlConnection conn)
        {
            System.DateTime startTime = System.DateTime.Now;
            SqlCommand myCommand = new SqlCommand(sql, conn);
            myCommand.CommandTimeout = 15000;

            while (rowa.Date.DateAndTime.DateDiff (rowa.Date.DateInterval.Second,startTime, System.DateTime.Now) < 20) 
            {
            try
            {
                myCommand.ExecuteNonQuery();
                return true;

            }
            catch (SqlException ex)
            {
                if (ex.Number != 1205)
                {
                    throw ex;
                }
                else
                {
                    rowa.messaging.Syslog sy1 = new messaging.Syslog();
                    sy1.websend("Deadlock Exception");
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");
        }

        public static bool executeNonQuery(ref SqlParameter[] para, string spName, ref SqlConnection conn)
        {
            SqlCommand sqlCmd = new SqlCommand(spName, conn);
            sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
            sqlCmd.CommandTimeout = 15000;
            sqlCmd.Parameters.AddRange(para);

            System.DateTime startTime = System.DateTime.Now;
            while (rowa.Date.DateAndTime.DateDiff (rowa.Date.DateInterval.Second,startTime, System.DateTime.Now) < 20) 
            {
            try
            {
                sqlCmd.ExecuteNonQuery();
                return true;
            }
            catch (SqlException ex)
            {
                if (ex.Number != 1205)
                {
                    throw ex;
                }
                else
                {
                    rowa.messaging.Syslog sy1 = new messaging.Syslog();
                    sy1.websend("Deadlock Exception");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");
        }

        public static bool executeNonQuery(ref SqlCommand sqlCmd, ref SqlConnection conn)
        {
            System.DateTime startTime = System.DateTime.Now;
            while (rowa.Date.DateAndTime.DateDiff(rowa.Date.DateInterval.Second, startTime, System.DateTime.Now) < 20)
            {
                try
                {
                    sqlCmd.ExecuteNonQuery();
                    return true;
                }
                catch (SqlException ex)
                {
                    if (ex.Number != 1205)
                    {
                        throw ex;
                    }
                    else
                    {
                        rowa.messaging.Syslog sy1 = new messaging.Syslog();
                        sy1.websend("Deadlock Exception");
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");
        }

    }



    public class datasets
    {
        public static DataSet getDataset(XmlDocument xmlDoc)
        {
            DataSet dataset = new DataSet();
            dataset.ReadXml(new XmlNodeReader(xmlDoc));
            return dataset;
        }

    
        public static void deleteRow(DataSet ds, string filtervalue, string filtercolumn, string tablename)
        {
            try
            {
                foreach (DataRow row in ds.Tables[tablename].Select(filtercolumn + "='" + filtervalue + "'"))
                {
                    row.Delete();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static DataTable selectTable(DataSet ds, string filter, string tablename)
        {
            try
            {
                DataView dvView = ds.Tables[tablename].DefaultView;
                dvView.RowFilter  = filter;
                DataTable dtFiltered = dvView.ToTable();
                return dtFiltered;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static DataTable sortTable(DataSet ds, string sortcolumn, string tablename)
        {
            try
            {

                DataView dvView = ds.Tables[tablename].DefaultView;
                dvView.Sort = sortcolumn;
                DataTable dtSort = dvView.ToTable();
                return dtSort;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }




        /// <summary>
        /// über eine StoredProcedure wird hier ein Dataset erstellt. Umweg geht jedoch über einen Konverter welcher Zeile für Zeile dem Dataset den Eintrag macht.
        /// </summary>
        /// <param name="para">SQL Parameter</param>
        /// <param name="conn">die SQL Connection</param>
        /// <param name="spName">die verwendete Stored Procedure</param>
        /// <returns></returns>
        /// <remarks></remarks>

        public DataSet getDataset(ref SqlParameter[] para, string spName, ref SqlConnection conn)
        {
            SqlCommand sqlCmd = new SqlCommand(spName, conn);
            sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
            sqlCmd.CommandTimeout = 15000;
            sqlCmd.Parameters.AddRange(para);

            System.DateTime startTime = System.DateTime.Now;
            while (rowa.Date.DateAndTime.DateDiff (rowa.Date.DateInterval.Second,startTime, System.DateTime.Now) < 20) 
            {
                try
                {
                    DataSet ds = rowa.data.helpers.ConvertDataReadertoDataSet(sqlCmd.ExecuteReader());
                    return ds.Copy();
                }
                catch (SqlException ex)
                {
                    if (ex.Number != 1205)
                    {
                        throw ex;
                    }
                    else
                    {
                        rowa.messaging.Syslog sy1 = new messaging.Syslog();
                        sy1.websend("Deadlock Exception");
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");
        }

        public DataSet getDataset(ref SqlParameter[] para, string spName, ref SqlParameter returnpara, ref SqlConnection conn)
        {
            SqlCommand sqlCmd = new SqlCommand(spName, conn);
            sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
            sqlCmd.CommandTimeout = 15000;
            sqlCmd.Parameters.AddRange(para);
            sqlCmd.Parameters.Add(returnpara).Direction = ParameterDirection.ReturnValue;

            System.DateTime startTime = System.DateTime.Now;
            while (rowa.Date.DateAndTime.DateDiff (rowa.Date.DateInterval.Second,startTime, System.DateTime.Now) < 20) 
            {
            try
            {
                DataSet ds = rowa.data.helpers.ConvertDataReadertoDataSet(sqlCmd.ExecuteReader());
                return ds.Copy();
            }
            catch (SqlException ex)
            {
                if (ex.Number != 1205)
                {
                    throw ex;
                }
                else
                {
                    rowa.messaging.Syslog sy1 = new messaging.Syslog();
                    sy1.websend("Deadlock Exception");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");
        }




        /// <summary>
        /// hier wird ein Dataset generiert
        /// </summary>
        /// <param name="sql">SQL String</param>
        /// <param name="conn">SQl Connection</param>
        /// <param name="unCached">true if data should be fetched directly from database instead of cache</param>
        /// <returns>Dataset</returns>
        /// <remarks></remarks>
        public DataSet getDataset(string sql, ref SqlConnection conn)
        {
            DataSet ds = new DataSet();

            SqlCommand myCommand = new SqlCommand(sql, conn);
            myCommand.CommandTimeout = 15000;
            SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
            myAdapter.AcceptChangesDuringUpdate = false;
            myAdapter.AcceptChangesDuringFill = false;

            System.DateTime startTime = System.DateTime.Now;
            while (rowa.Date.DateAndTime.DateDiff (rowa.Date.DateInterval.Second,startTime, System.DateTime.Now) < 20) 
            {
            try
            {
                myAdapter.Fill(ds);
                return ds.Copy();
            }
            catch (SqlException ex)
            {
                if (ex.Number != 1205)
                {
                    throw ex;
                }
                else
                {
                    rowa.messaging.Syslog sy1 = new messaging.Syslog();
                    sy1.websend("DL EX:" + sql);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");
        }

        public DataSet getDataset(string url, int timeout)
        {
            string xmlSourceStatus;
            StreamReader xmlStream;
            xmlStream = null;
            DataSet ds = new DataSet();
            try
            {
                if (url.StartsWith("http"))
                {
                    xmlSourceStatus = rowa.web.urls.Check(url, timeout);
                    if (xmlSourceStatus.ToLower().Contains("ok"))
                    {
                        // mach HTTP
                        System.Net.HttpWebRequest xmlRequest;
                        xmlRequest = ((System.Net.HttpWebRequest)(System.Net.WebRequest.Create(url)));
                        xmlRequest.Timeout = timeout;
                        xmlRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
                        System.Net.HttpWebResponse xmlResponse = ((System.Net.HttpWebResponse)(xmlRequest.GetResponse()));
                        xmlStream = new StreamReader(xmlResponse.GetResponseStream());

                    }
                    else
                    {
                        throw new Exception(xmlSourceStatus);
                    }
                }
                else
                {
                    // mach file
                    xmlStream = new StreamReader(url);
                }

               
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                try
                {
                    ds.ReadXml(xmlStream);
                    xmlStream.Close();
                    

                }
                catch { }
            }
            return ds;
        }


        public DataSet getDataset(string sql, ref System.Data.Odbc.OdbcConnection conn)
        {
            try
            {
                DataSet ds = new DataSet();
                System.Data.Odbc.OdbcCommand myCommand = new System.Data.Odbc.OdbcCommand(sql, conn);
                myCommand.CommandTimeout = 15000;
                System.Data.Odbc.OdbcDataAdapter myAdapter = new System.Data.Odbc.OdbcDataAdapter(myCommand);
                myAdapter.AcceptChangesDuringUpdate = false;
                myAdapter.AcceptChangesDuringFill = false;
                myAdapter.Fill(ds);
                return ds.Copy();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        public DataSet getDataset(string sql, ref System.Data.OleDb.OleDbConnection  conn)
        {
            try
            {
                DataSet ds = new DataSet();
                System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand(sql, conn);
                myCommand.CommandTimeout = 15000;
                System.Data.OleDb.OleDbDataAdapter myAdapter = new System.Data.OleDb.OleDbDataAdapter(myCommand);
                myAdapter.AcceptChangesDuringUpdate = false;
                myAdapter.AcceptChangesDuringFill = false;
                myAdapter.Fill(ds);
                return ds.Copy();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        public DataSet getDataset(string xmlString)
        {
            DataSet output = null;
            if (String.IsNullOrEmpty(xmlString))
            {
                return output;
            }

            try
            {
                using (StringReader stringReader = new StringReader(xmlString))
                {
                    output = new DataSet();
                    output.ReadXml(stringReader);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return output;
        }


    }

    public class values
    {

        public string getValue(string sql, ref System.Data.SqlClient.SqlConnection connection)
        {
            object output;
            SqlCommand sqlCmd = new SqlCommand(sql, connection);

            System.DateTime startTime = System.DateTime.Now;
            while (rowa.Date.DateAndTime.DateDiff (rowa.Date.DateInterval.Second,startTime, System.DateTime.Now) < 20) 
            {
            try
            {
                output = sqlCmd.ExecuteScalar();
                if (output != null && !(output is DBNull))
                {
                    return output.ToString();
                }
                return string.Empty;
            }
            catch (SqlException ex)
            {
                if (ex.Number != 1205)
                {
                    throw ex;
                }
                else
                {
                    rowa.messaging.Syslog sy1 = new messaging.Syslog();
                    sy1.websend("DL EX:" + sql);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");
        }

        public string getValue(string sql, string standard, ref System.Data.SqlClient.SqlConnection connection)
        {
            object output;
            SqlCommand sqlCmd = new SqlCommand(sql, connection);

            System.DateTime startTime = System.DateTime.Now;
            while (rowa.Date.DateAndTime.DateDiff (rowa.Date.DateInterval.Second,startTime, System.DateTime.Now) < 20) 
            {
            try
            {
                output = sqlCmd.ExecuteScalar();
                if (output != null && !(output is DBNull))
                {
                    return output.ToString();
                }
                return standard;
            }
            catch (SqlException ex)
            {
                if (ex.Number != 1205)
                {
                    throw ex;
                }
                else
                {
                    rowa.messaging.Syslog sy1 = new messaging.Syslog();
                    sy1.websend("DL EX:" + sql);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");
        }

        public string getValue(string Field, string Table, string where, string standard, ref System.Data.SqlClient.SqlConnection connection)
        {
            object output;
            SqlCommand sqlCmd = new SqlCommand("select top 1 [" + Field + "] from dbo.[" + Table.Replace("dbo.", "") + "] " + where + "", connection);

            System.DateTime startTime = System.DateTime.Now;
            while (rowa.Date.DateAndTime.DateDiff (rowa.Date.DateInterval.Second,startTime, System.DateTime.Now) < 20) 
            {
            try
            {
                output = sqlCmd.ExecuteScalar();
                if (output != null && !(output is DBNull))
                {
                    return output.ToString();
                }
                return standard;
            }
            catch (SqlException ex)
            {
                if (ex.Number != 1205)
                {
                    throw ex;
                }
                else
                {
                    rowa.messaging.Syslog sy1 = new messaging.Syslog();
                    sy1.websend("Deadlock Exception");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            }
            rowa.messaging.Syslog sy = new messaging.Syslog();
            sy.websend("Deadlock Loop Exception");
            throw new Exception("Deadlock Loop Exception");
        }
    }



    public class datatables
    {
        public DataTable getDataTable(string sql, ref System.Data.SqlClient.SqlConnection conn)
        {
            DataTable dt = new DataTable() ;
            try
            {
                data.datasets dsProc = new datasets();
                dt = dsProc.getDataset(sql, ref conn).Tables[0];
            }
            catch(Exception ex)
            {
                throw ex;
            }
           return dt;
        }
        public DataTable getDataTable(string sql, ref System.Data.Odbc.OdbcConnection  conn)
        {
            DataTable dt = new DataTable();
            try
            {
                data.datasets dsProc = new datasets();
                dt = dsProc.getDataset(sql, ref conn).Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return dt;
        }
        public DataTable getDataTable(string sql, ref System.Data.OleDb.OleDbConnection  conn)
        {
            DataTable dt = new DataTable();
            try
            {
                data.datasets dsProc = new datasets();
                dt = dsProc.getDataset(sql, ref conn).Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return dt;
        }


        public static DataTable selectTable(DataTable  dt, string filter)
        {
            try
            {
                DataSet ds = new DataSet();
                ds.Tables.Add(dt.Clone());
                DataView dvView = ds.Tables[0].DefaultView;
                dvView.RowFilter = filter;
                DataTable dtFiltered = dvView.ToTable();
                return dtFiltered;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static DataTable sortTable(DataTable dt, string sortcolumn)
        {
            try
            {
                DataSet ds = new DataSet();
                ds.Tables.Add(dt.Clone());
                DataView dvView = ds.Tables[0].DefaultView;
                dvView.Sort = sortcolumn;
                DataTable dtSort = dvView.ToTable();
                return dtSort;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


    }


    public class structureedit
    {
        public static void addColumn(ref DataTable dt, string DataColumnName)
        {
            DataColumn dc;
            dc = new DataColumn(DataColumnName );
            dt.Columns.Add(dc);
        }
        public static void addDataTable(ref DataSet ds, string DataTableName)
        {
            DataTable dt = new DataTable(DataTableName);
            ds.Tables.Add(dt);
        }
    }
}

namespace rowa.Date
{
    public enum DateInterval
    {
        Day,
        DayOfYear,
        Hour,
        Minute,
        Month,
        Quarter,
        Second,
        Weekday,
        WeekOfYear,
        Year
    }

    public class DateAndTime
    {
        public static string Date2String(Object Date, string Format)
        {
            return rowa.vbfunctions.Date.Date2String(Date, Format);
        }

        public static long DateDiff(DateInterval interval, DateTime dt1, DateTime dt2)
        {
            return DateDiff(interval, dt1, dt2, System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);
        }

        private static int GetQuarter(int nMonth)
        {
            if (nMonth <= 3)
                return 1;
            if (nMonth <= 6)
                return 2;
            if (nMonth <= 9)
                return 3;
            return 4;
        }

        public static long DateDiff(DateInterval interval, DateTime dt1, DateTime dt2, DayOfWeek eFirstDayOfWeek)
        {
            if (interval == DateInterval.Year)
                return dt2.Year - dt1.Year;

            if (interval == DateInterval.Month)
                return (dt2.Month - dt1.Month) + (12 * (dt2.Year - dt1.Year));

            TimeSpan ts = dt2 - dt1;

            if (interval == DateInterval.Day || interval == DateInterval.DayOfYear)
                return Round(ts.TotalDays);

            if (interval == DateInterval.Hour)
                return Round(ts.TotalHours);

            if (interval == DateInterval.Minute)
                return Round(ts.TotalMinutes);

            if (interval == DateInterval.Second)
                return Round(ts.TotalSeconds);

            if (interval == DateInterval.Weekday)
            {
                return Round(ts.TotalDays / 7.0);
            }

            if (interval == DateInterval.WeekOfYear)
            {
                while (dt2.DayOfWeek != eFirstDayOfWeek)
                    dt2 = dt2.AddDays(-1);
                while (dt1.DayOfWeek != eFirstDayOfWeek)
                    dt1 = dt1.AddDays(-1);
                ts = dt2 - dt1;
                return Round(ts.TotalDays / 7.0);
            }

            if (interval == DateInterval.Quarter)
            {
                double d1Quarter = GetQuarter(dt1.Month);
                double d2Quarter = GetQuarter(dt2.Month);
                double d1 = d2Quarter - d1Quarter;
                double d2 = (4 * (dt2.Year - dt1.Year));
                return Round(d1 + d2);
            }

            return 0;

        }

        private static long Round(double dVal)
        {
            if (dVal <= 0)
                return (long)Math.Floor(dVal);
            return (long)Math.Ceiling(dVal);
        }
    }
}

namespace rowa.Date.FeierTage
{

    /// <summary>
    /// Und nochmal eine Feiertagsberechnung 
    /// </summary>
    public class FeierTage
    {
        private List<FeierTag> feiertage = new List<FeierTag>();

        public FeierTage()
        {
            Initial();
        }


        /// <summary>
        /// Den möglichen Feiertags anhand des Datums und des jeweiligen Bundes Landes ermitteln
        /// </summary>
        /// <param name="datum">Das Datum, daß zur ermittlung herrangezogen werden soll</param>
        /// <param name="land">Das jeweilige Land</param>
        /// <returns>Der jeweilige Feiertag als Text</returns>
        public String GetFeiertag(DateTime datum, Land land)
        {

            // Liste der Feiertage durchgehen
            foreach (FeierTag f in feiertage)
            {
                if (datum.ToShortDateString().Equals(f.GetDatum(GetOstersonntag(datum.Year)).ToShortDateString()))
                {
                    // Prüfen ob das Land enthalten ist
                    foreach (Land l in f.Länder)
                    {
                        if (land == l)
                        {
                            return f.Feiertag;
                        }
                    }
                }
            }
            return "";
        }

        /// <summary>
        /// Einfache Abfrage ob das übergeben Datum in dem jeweiligen Land ein Feiertag ist
        /// </summary>
        /// <param name="datum">Das Datum, daß zur ermittlung herrangezogen werden soll</param>
        /// <param name="land">Das jeweilige Land</param>
        /// <returns>Wahr oder Falsch</returns>
        public Boolean IsFeiertag(DateTime date, Land land)
        {
            return (GetFeiertag(date, land).Length > 0);
        }

        /// <summary>
        /// Errechnet das Datum des Ostersonntags aus dem übergebenen Jahr
        /// </summary>
        /// <param name="int">Das Jahr in YYYY Schreibweise</param>
        /// <returns>Das errechnete Datum des Ostersonnsags in dem angegebene Jahr</returns>
        private DateTime GetOstersonntag(int jahr)
        {
            int c;
            int i;
            int j;
            int k;
            int l;
            int n;
            int OsterTag;
            int OsterMonat;

            c = jahr / 100;
            n = jahr - 19 * ((int)(jahr / 19));
            k = (c - 17) / 25;
            i = c - c / 4 - ((int)(c - k) / 3) + 19 * n + 15;
            i = i - 30 * ((int)(i / 30));
            i = i - (i / 28) * ((int)(1 - (i / 28)) * ((int)(29 / (i + 1))) * ((int)(21 - n) / 11));
            j = jahr + ((int)jahr / 4) + i + 2 - c + ((int)c / 4);
            j = j - 7 * ((int)(j / 7));
            l = i - j;

            OsterMonat = 3 + ((int)(l + 40) / 44);
            OsterTag = l + 28 - 31 * ((int)OsterMonat / 4);

            return Convert.ToDateTime(jahr + "-" + OsterMonat  + "-" + OsterTag.ToString());
        }


        /// <summary>
        /// Die einzelnen möglichen Feiertage 
        /// kan natürlich noch erweitert werden
        /// </summary>
        private void Initial()
        {
            Land[] alle = new Land[] { Land.Baden_Würtenberg, Land.Bayern, Land.Berlin, Land.Brandenburg, Land.Bremen, Land.Hamburg, Land.Hessen, Land.Mecklenburg_Vorpommern, Land.Niedersachsen, Land.Nordrhein_Westfalen, Land.Rheinland_Pfalz, Land.Saarland, Land.Sachsen, Land.Sachsen_Anhalt, Land.Schleswig_Holstein, Land.Thüringen };

            feiertage.Add(new FeierTag("Neujahr", "01-01", FeiertagsArt.Fester_Feiertag, alle));
            feiertage.Add(new FeierTag("Heiligen Drei Könige", "01-06", FeiertagsArt.Fester_Feiertag, new Land[] { Land.Baden_Würtenberg, Land.Bayern, Land.Sachsen_Anhalt }));
            feiertage.Add(new FeierTag("Karfreitag", -2, FeiertagsArt.Bewegliche_Feiertag, alle));
            feiertage.Add(new FeierTag("Ostersonntag", 0, FeiertagsArt.Bewegliche_Feiertag, alle));
            feiertage.Add(new FeierTag("Ostermontag", 1, FeiertagsArt.Bewegliche_Feiertag, alle));
            feiertage.Add(new FeierTag("Tag der Arbeit", "05-01", FeiertagsArt.Fester_Feiertag, alle));
            feiertage.Add(new FeierTag("Christi Himmelfahrt", 39, FeiertagsArt.Bewegliche_Feiertag, alle));
            feiertage.Add(new FeierTag("Pfingstsonntag", 49, FeiertagsArt.Bewegliche_Feiertag, alle));
            feiertage.Add(new FeierTag("Pfingstmontag", 50, FeiertagsArt.Bewegliche_Feiertag, alle));
            feiertage.Add(new FeierTag("Fronleichnam", 60, FeiertagsArt.Bewegliche_Feiertag, new Land[] { Land.Baden_Würtenberg, Land.Bayern, Land.Hessen, Land.Nordrhein_Westfalen, Land.Rheinland_Pfalz, Land.Saarland }));
            feiertage.Add(new FeierTag("Mariä Himmelfahrt", "08-15", FeiertagsArt.Fester_Feiertag, new Land[] { Land.Saarland }));
            feiertage.Add(new FeierTag("Tag der dt. Einheit", "10-03", FeiertagsArt.Fester_Feiertag, alle));
            feiertage.Add(new FeierTag("Allerheiligen", "11-01", FeiertagsArt.Fester_Feiertag, new Land[] { Land.Baden_Würtenberg, Land.Bayern, Land.Nordrhein_Westfalen, Land.Rheinland_Pfalz, Land.Saarland }));
            feiertage.Add(new FeierTag("1. Weinachtstag", "12-25", FeiertagsArt.Fester_Feiertag, alle));
            feiertage.Add(new FeierTag("2. Weinachtstag", "12-26", FeiertagsArt.Fester_Feiertag, alle));

        }
    }

    /// <summary>
    /// Die eigentliche Klasse der einzelnen Feiertage
    /// </summary>
    internal class FeierTag
    {
        private FeiertagsArt art;
        private string feiertag;
        private DateTime datum;
        private string testDatum;
        private int tageHinzu;
        private Land[] länder;

        public String Feiertag
        {
            get
            {
                return this.feiertag;
            }
        }
        public DateTime Datum
        {
            get
            {
                return this.datum;
            }
        }
        public Land[] Länder
        {
            get
            {
                return länder;
            }
        }

        internal FeierTag(String feiertag, String testDatum, FeiertagsArt art, Land[] länder)
        {
            this.feiertag = feiertag;
            this.testDatum = testDatum;
            this.tageHinzu = 0;
            this.art = art;
            this.länder = länder;
        }
        internal FeierTag(String feiertag, int tageHinzu, FeiertagsArt art, Land[] länder)
        {
            this.feiertag = feiertag;
            this.tageHinzu = tageHinzu;
            this.art = art;
            this.länder = länder;
        }

        public DateTime GetDatum(DateTime osterSonntag)
        {
            if (this.art != FeiertagsArt.Fester_Feiertag)
            {
                datum = osterSonntag.AddDays(this.tageHinzu);
            }
            else
            {
                datum = DateTime.Parse(osterSonntag.Year + "-" + testDatum);
            }

            return DateTime.Parse(osterSonntag.Year + "-" + datum.Month.ToString() + "-" + datum.Day.ToString() );
        }
    }

    public enum Land
    {
        Baden_Würtenberg,
        Bayern,
        Berlin,
        Brandenburg,
        Bremen,
        Hamburg,
        Hessen,
        Mecklenburg_Vorpommern,
        Niedersachsen,
        Nordrhein_Westfalen,
        Rheinland_Pfalz,
        Saarland,
        Sachsen,
        Sachsen_Anhalt,
        Schleswig_Holstein,
        Thüringen
    }
    public enum FeiertagsArt
    {
        Fester_Feiertag,
        Bewegliche_Feiertag
    }
}



namespace rowa.calculation
    {
        public class prozentrechnung
        {
            //http://www.brinkmann-du.de/mathe/fos/wieder03_01.htm
            public static int BerechnungProzentsatz(int alterWert, int neuerWert)
            {
                try
                {
                    int g = alterWert;
                    int w = neuerWert - alterWert;
                    return (w * 100) / g;
                }
                catch
                {
                    return 0;
                }

            }

        }
        public class math
        {
            /// <summary>
            /// Rundet kaufmännisch auf die Anzahl der übergebenen Nachkommastellen
            ///
            /// Achtung: Seit .NET 2.0 gibt es folgende Überladung die dieses Snippet hinfällig machen: Math.Round(3.65m,1,MidpointRounding.AwayFromZero)
            /// </summary>
            /// <param name="value">Zu rundender Wert</param>
            /// <param name="dec">Anzahl der Nachkommastellen</param>
            /// <returns>Gerundeter Wert</returns>
            public static decimal CommercialRound(decimal value, int dec)
            {
                // um die Anzahl der Dezimalstellen nach links verschieben
                decimal x = value * Convert.ToDecimal(Math.Pow(10, dec));

                // Dezimalstellen abtrennen
                decimal y = Math.Floor(x);

                // ist die Differenz größer oder gleich 0.5 soll aufgerundet werden
                if ((x - y) >= 0.5m) y++;

                // um die Anzahl der Dezimalstellen nach rechts verschieben 
                return y / Convert.ToDecimal(Math.Pow(10, dec));
            }

        }

        public class date
        {
            /// <summary>
            /// Gets the age of eg. a person from its birthday.
            /// </summary>
            /// <param name="birthday">The birthday.</param>
            /// <returns>The age in years.</returns>
            public static int GetAgeFromDate(DateTime birthday)
            {
                int years = DateTime.Now.Year - birthday.Year;
                birthday = birthday.AddYears(years);
                if (DateTime.Now.CompareTo(birthday) < 0) { years--; }
                return years;
            }

            public static int berechneKalenderwoche(DateTime datum)
            {
                int kalenderwoche = (datum.DayOfYear / 7) + 1;
                if (kalenderwoche == 53) kalenderwoche = 1;
                return kalenderwoche;
            }


        }


    }
namespace rowa.fileservice
    {
    using System;
    using System.IO;
    using System.DirectoryServices;
    using System.DirectoryServices.AccountManagement;
    using System.Security.AccessControl;
    using System.Security.Principal;
    using System.Security.Permissions;
        using System.Collections;

    /// <summary>
    /// Directory size class with recursive sub directory inclusion
    /// 
    /// (c) Copyright Vincent Wochnik 2007
    /// </summary>
    public class DirectorySize
    {
        /// <summary>
        /// Returns the size of a directory
        /// </summary>
        /// <param name="path">Path to directory</param>
        /// <param name="includeSubDirectories">Specifyes, wheather sub directories are included</param>
        /// <returns>Directory size</returns>
        public static long GetDirectorySize(string path, bool includeSubDirectories)
        {
            long size = 0;

            // get sub directories (recursive)
            if (includeSubDirectories)
            {
                try
                {
                    string[] subDirectories = Directory.GetDirectories(path);
                    foreach (string subDirectory in subDirectories)
                        try
                        {
                            size += GetDirectorySize(subDirectory, includeSubDirectories);
                        }
                        catch 
                        {
                        }
                }
                catch { /* what should we do??? */ }
            }

            // get files and add size
            try
            {
                    string[] fileNames = Directory.GetFiles(path);
                foreach (string fileName in fileNames)
                {
                    FileInfo fileInfo = new FileInfo(fileName);
                    size += fileInfo.Length;
                }
            }
            catch { /* what should we do??? */ }

            return size;
        }
    }
    public class security

    {
        public static void AddFileSecurity(string fileName, string account,
            FileSystemRights rights, AccessControlType controlType)
        {

            // Get a FileSecurity object that represents the 
            // current security settings.
            FileSecurity fSecurity = File.GetAccessControl(fileName);

            // Add the FileSystemAccessRule to the security settings. 
            fSecurity.AddAccessRule(new FileSystemAccessRule(account,
                rights, controlType));

            // Set the new access settings.
            File.SetAccessControl(fileName, fSecurity);

        }


        //setzt neue Berechtigungen für Bunutzer

        public void SetDirectorySecurity(string DomainName, string AccountName, string Path, FileSystemRights Rights)
        {
            DirectorySecurity dirSecurity = Directory.GetAccessControl(Path);
            FileSystemAccessRule Rule = new FileSystemAccessRule(AccountName, Rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
            dirSecurity.ResetAccessRule(Rule);
            DirectoryInfo dirInfo = new DirectoryInfo(Path);
            dirInfo.SetAccessControl(dirSecurity);
        }

        //löschen eines Beunutzers aus der Berechtigungen
        //wird hier allerdings nicht benutzt
        public void RemoveUserToDirectorySecurity(string DomainName, string AccountName, string Path)
        {
            DirectorySecurity dirSecurity = Directory.GetAccessControl(Path);
            FileSystemAccessRule Rule = new FileSystemAccessRule(AccountName, FileSystemRights.FullControl, AccessControlType.Allow);
            dirSecurity.RemoveAccessRuleAll(Rule);
            DirectoryInfo d = new DirectoryInfo(Path);
            d.SetAccessControl(dirSecurity);
        }
    }

    public class textfiles
    {
        public static void  ReplaceLine(string filepath, string contains, string newline)
        {
            // erstmal alles einlesen und in eine Arraylist einfügen
            StreamReader objReader = new StreamReader(filepath);
            string sLine = "";
            ArrayList arrText = new ArrayList();
            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null)
                    arrText.Add(sLine);
            }
            objReader.Close();


            StreamWriter myFile = new StreamWriter(filepath, false);
            foreach (string sOutput in arrText)
            {
                // hier zeilenweise neue datei schreiben:
                if (sOutput.Contains (contains) == true )
                {
                       myFile.WriteLine(newline);
                }
                else
                {
                    myFile.WriteLine(sOutput );
                }
            }
            myFile.Close();
        }

        public static string readTextfile(string pfad)
        {
            if (System.IO.File.Exists(pfad) == true)
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(pfad, System.Text.Encoding.UTF8);
                System.Text.StringBuilder output = new System.Text.StringBuilder();
                //Dim style As String = ""
                string line;
                do
                {
                    line = sr.ReadLine();
                    output.AppendLine(line);
                }
                while (!(line == null));
                sr.Close();
                sr.Dispose();
                sr = null;
                return output.ToString();
            }
            else
            {
                return "";
            }
        }

        public static string readTextfile(string pfad, Encoding encoding)
        {
            if (System.IO.File.Exists(pfad) == true)
            {
                StreamReader sr = new StreamReader(pfad, encoding);

                System.Text.StringBuilder output = new System.Text.StringBuilder();
                //Dim style As String = ""
                string line;
                do
                {
                    line = sr.ReadLine();
                    output.AppendLine(line);
                }
                while (!(line == null));
                sr.Close();
                sr.Dispose();
                sr = null;
                return output.ToString();
            }
            else
            {
                return "";
            }
        }



    }



    public class fileHelpers
    {
        public static bool isFileDifferent(string p_FileA, string p_FileB)
        {
            bool retVal = true;
            FileInfo infoA = null;
            FileInfo infoB = null;
            byte[] bufferA = new byte[128];
            byte[] bufferB = new byte[128];
            int bufferRead = 0;

            // Die Dateien überprüfen
            if (!File.Exists(p_FileA))
            {
                throw new ArgumentException(String.Format("Die Datei '{0}' konnte nicht gefunden werden", p_FileA), "p_FileA");
            }
            if (!File.Exists(p_FileB))
            {
                throw new ArgumentException(String.Format("Die Datei '{0}' konnte nicht gefunden werden", p_FileB), "p_FileB");
            }

            // Dateiinfo wegen der Dateigröße erzeugen
            infoA = new FileInfo(p_FileA);
            infoB = new FileInfo(p_FileB);

            // Wenn die Dateigröße gleich ist, dann einen Vergleich anstossen
            if (infoA.Length == infoB.Length)
            {
                // Binärvergleich
                using (BinaryReader readerA = new BinaryReader(File.OpenRead(p_FileA)))
                {
                    using (BinaryReader readerB = new BinaryReader(File.OpenRead(p_FileB)))
                    {
                        // Dateistream blockweise über Puffer einlesen
                        while ((bufferRead = readerA.Read(bufferA, 0, bufferA.Length)) > 0)
                        {
                            // Dateigrößen sind gleich, deshalb kann hier
                            // ungeprüft auch von der 2. Datei eingelesen werden
                            readerB.Read(bufferB, 0, bufferB.Length);

                            // Bytevergleich innerhalb des Puffers
                            for (int i = 0; i < Math.Min(bufferA.Length, bufferRead); i++)
                            {
                                if (bufferA[i] != bufferB[i])
                                {
                                    retVal = false;
                                    break;
                                }
                            }

                            // Wenn Vergleich bereits fehlgeschlagen, dann hier schon abbruch
                            if (!retVal)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            else
            {
                // Die Dateigröße ist schon unterschiedlich
                retVal = false;
            }

            return retVal;
        }



        public static bool isFileFound(string path, string fileName)
        {
            System.IO.FileInfo fi = null;

            bool found = false;
            try
            {
                fi = new System.IO.FileInfo(path + fileName);
                found = true;
            }
            catch
            {
                found = fi.Exists;
            }

            return found;
        }

        public static bool isFileFound(string fullfileName)
        {
            System.IO.FileInfo fi = null;

            bool found = false;
            try
            {
                fi = new System.IO.FileInfo(fullfileName);
                found = fi.Exists;
            }
            catch
            {
                found = false;
            }

            return found;
        }

        public static List<string> getFilesInDirectories(string path)
        {
            List<string> DirFiles = new List<string>();
            if (System.IO.Directory.Exists(path))
            {
                DirectoryInfo di = new DirectoryInfo(path);
                foreach (FileInfo fi in di.GetFiles())
                    DirFiles.Add(fi.Name);
            }
            return DirFiles;
        }

        public static List<string> getDirectoriesInDirectories(string path)
        {
            List<string> DirFiles = new List<string>();
            if (System.IO.Directory.Exists(path))
            {
                DirectoryInfo di = new DirectoryInfo(path);
                foreach (DirectoryInfo i in di.GetDirectories())
                    DirFiles.Add(i.Name);
            }
            return DirFiles;
        }



        /// <summary>
        /// Diese Funktion entfernt alle Zeichen aus dem übergebenen String
        /// die in Dateinamen nicht erlaubt sind.
        /// </summary>
        /// <param name="Input">Der zu prüfende String</param>
        /// <returns>String ohne nichterlaubte Zeichen</returns>
        private string AdjustPath(string Input)
        {
            return System.Text.RegularExpressions.Regex.Replace(Input, @"[\\/:*?""<>|]", string.Empty);
        }

        /// <summary>
        /// prüft ob ein Ordner oder eine Datei existiert
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool ifExists(string path)
        {
            if (System.IO.Directory.Exists(path))
            {
                return true;
            }
            if (System.IO.File.Exists(path))
            {
                return true;
            }
            return false;
        }

    }



    }
namespace rowa.helpers
{
    public class forApplications
    {
        /// <summary>
        /// gibt ein Argument bei der Argumentübergabe für Konsolenanwendungen zurück
        /// </summary>
        /// <param name="args">Args aus "main"</param>
        /// <param name="arg">welches Argument ohne - und =</param>
        /// <returns></returns>
        public static string getArguments(string[] args, string arg)
        {
            
            foreach (string var in args)
            {
                if (var.ToLower().StartsWith("-" + arg.ToLower()  + "="))
                {
                    return var.Remove(0, arg.Length + 2);
                }
            }
            return "";
        }

        /// <summary>
        /// Prüft, ob ein Typ (null)-Werte annehmen kann oder nicht
        /// </summary>
        /// <param name="type">Typ, der geprüft werden soll</param>
        /// <returns>Kann (null)-Werte annehmen (true) oder nicht (false)</returns>
        public static bool IsNullable(Type type)
        {
            if (null == type)
            {
                throw new ArgumentNullException("type");
            }

            if (!type.IsValueType)
            {
                // kein Wertetyp, daher kann der Typ (null)-Werte annehmen
                return true;
            }

            // Wenn Nullable.GetUnderlyingType() einen übergeordneten Typ ermitteln kann,
            // bedeutet dies, dass dies ein Wertetyp ist, der (null)-Werte annehmen kann,
            // z.B. bool?
            return Nullable.GetUnderlyingType(type) is Type;
        }

        public static string GetApplicationsPath()
        {
            FileInfo fi = new FileInfo(Assembly.GetEntryAssembly().Location);
            return fi.DirectoryName;
        } 


    }

}
namespace rowa.vbfunctions
{
    public class Date
    {
        public static bool IsDate(object sdate)
        {
            DateTime dt;
            bool isDate = true;
            try
            {
                string date = Convert.ToString(sdate);
                dt = DateTime.Parse(date);
            }
            catch
            {
                isDate = false;
            }
            return isDate;
        }

        public static string Date2String(Object Date, string Format)
        {
            if (IsDate(Date))
            {
                DateTime Datum = Convert.ToDateTime(Date);
                Format = Format.Replace("YYYY", Datum.Year.ToString());
                Format = Format.Replace("YY", Datum.Year.ToString());
                if (Datum.Month.ToString().Length == 1)
                {
                    Format = Format.Replace("MM", "0" + Datum.Month);
                }
                else
                {
                    Format = Format.Replace("MM", Datum.Month.ToString());
                }
                if (Datum.Day.ToString().Length == 1)
                {
                    Format = Format.Replace("DD", "0" + Datum.Day);
                }
                else
                {
                    Format = Format.Replace("DD", Datum.Day.ToString());
                }
                if (Datum.Minute.ToString().Length == 1)
                {
                    Format = Format.Replace("mm", "0" + Datum.Minute.ToString());
                }
                else
                {
                    Format = Format.Replace("mm", Datum.Minute.ToString());
                }
                if (Datum.Hour.ToString().Length == 1)
                {
                    Format = Format.Replace("hh", "0" + Datum.Hour.ToString());
                }
                else
                {
                    Format = Format.Replace("hh", Datum.Hour.ToString());
                }
                return Format;
            }
            else
            {
                return "";
            }
        }
    }


}

namespace rowa.security
{
    public class encrypt
    {
        public static string md5hash(string var)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(var, "md5");
        }
    }

    public class base64
    {
        public static string encrypt(string var)
        {
            return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(var));
        }
        public static string decrypt(string var)
        {
            return  System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(var));
        }


    }

}




namespace rowa.web
{
    using System.Net ;
    using System.Windows.Forms;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Text.RegularExpressions;
    using System.Xml;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;

   
    public class Content
    {
        public enum ContentType : int
        {
            application_json = 1,
            text_javascript = 2,
            text_xml = 3,
            application_ms_excel = 4,
            text_css = 5

        
        }


        /// <summary>
        /// sendet eine 401 Meldung
        /// </summary>
        /// <remarks></remarks>
        public static void send401()
        {
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Status = "401 Unauthorized";
            System.Web.HttpContext.Current.Response.AddHeader("WWW-Authenticate", "NTLM");
            System.Web.HttpContext.Current.Response.Write("<html><head><title>401 Unauthorized</title></head>");
            System.Web.HttpContext.Current.Response.Write("<body>");
            System.Web.HttpContext.Current.Response.Write("<h1>401 Unauthorized</h1>");
            System.Web.HttpContext.Current.Response.Write("</body>");
            System.Web.HttpContext.Current.Response.Write("</html>");
            //System.Web.HttpContext.Current.Response.End()
            //System.Web.HttpContext.Current.Response.Close()
            System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();

            //System.Web.HttpContext.Current.Response.End()
        }


        public string getLogin()
        {
            
         

            if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                try
                {
                    send401();
                    return System.Web.HttpContext.Current.User.Identity.Name;
                }
                catch
                {
                    return "";
                }
            }
            return System.Web.HttpContext.Current.User.Identity.Name;
        }


        /// <summary>
        /// sendet eine 401 Meldung
        /// </summary>
        /// <remarks></remarks>
        public static void send401(string realm)
        {
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Status = "401 Unauthorized";
            System.Web.HttpContext.Current.Response.AddHeader("WWW-Authenticate", "Basic Realm=\""+realm+"\"");
            System.Web.HttpContext.Current.Response.Write("<html><head><title>401 Unauthorized</title></head>");
            System.Web.HttpContext.Current.Response.Write("<body>");
            System.Web.HttpContext.Current.Response.Write("<h1>401 Unauthorized</h1>");
            System.Web.HttpContext.Current.Response.Write("</body>");
            System.Web.HttpContext.Current.Response.Write("</html>");
            //System.Web.HttpContext.Current.Response.End()
            //System.Web.HttpContext.Current.Response.Close()
            //System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest()

            //System.Web.HttpContext.Current.Response.End()
        }

        public string getLogin(string realm)
        {
            

            if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                try
                {
                    send401(realm);
                     return System.Web.HttpContext.Current.User.Identity.Name;
                }
                catch
                {
                    return "";
                }
            }
              return System.Web.HttpContext.Current.User.Identity.Name;
        }


        public static void SetContentType(ContentType ContentType)
        {
            switch (ContentType)
            {
                case ContentType.application_json:
                    System.Web.HttpContext.Current.Response.Charset = "utf-8";
                    System.Web.HttpContext.Current.Response.ContentType = "application/json";
                    break;
                case ContentType.text_javascript:
                    System.Web.HttpContext.Current.Response.Charset = "utf-8";
                    System.Web.HttpContext.Current.Response.ContentType = "text/javascript";
                    break;
                case ContentType.text_xml:
                    System.Web.HttpContext.Current.Response.Charset = "utf-8";
                    System.Web.HttpContext.Current.Response.ContentType = "text/xml";
                    break;
                case ContentType.application_ms_excel:
                    System.Web.HttpContext.Current.Response.Charset = "utf-8";
                    System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
                    break;
                case ContentType.text_css:
                    System.Web.HttpContext.Current.Response.Charset = "utf-8";
                    System.Web.HttpContext.Current.Response.ContentType = "text/css";
                    break;


            }

            

        }



        public static string readcontent(string url, System.Text.Encoding encoding)
        {
            try
            {
                WebClient wClient = new WebClient();
                wClient.Encoding = encoding ;
                return wClient.DownloadString(url);
            }
            catch
            {
                return "";
            }
        }

        public static string readcontent(string url)
        {
            try
            {
                WebClient wClient = new WebClient();
                return wClient.DownloadString(url);
            }
            catch 
            {
                return "";
            }
        }

        public static string readcontent(string url, string proxy)
        {
            try
            {
                WebClient wClient = new WebClient();
                WebProxy strProxy = new WebProxy(proxy ,true);
                strProxy.Credentials = CredentialCache.DefaultCredentials;
                wClient.Proxy = strProxy;
                return wClient.DownloadString(url);
            }
            catch
            {
                return "";
            }
        }

        public static Image ImageFromWeb(string url)
        {
            try
            {
                WebRequest oRequest = WebRequest.Create(url);
                oRequest.Method = "GET";
                WebResponse oResponse = oRequest.GetResponse();
                Image img = Image.FromStream(oResponse.GetResponseStream());
                oResponse.Close();
                return img;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static Image ImageFromWeb(string url, string proxy)
        {
            try
            {
                WebRequest oRequest = WebRequest.Create(url);
                oRequest.Method = "GET";

                WebProxy strProxy = new WebProxy(proxy, true);
                strProxy.Credentials = CredentialCache.DefaultCredentials;
                oRequest.Proxy = strProxy;
                WebResponse oResponse = oRequest.GetResponse();
                Image img = Image.FromStream(oResponse.GetResponseStream());
                oResponse.Close();
                return img;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void ImageFromWeb(string url, string path, ImageFormat format)
        {
            ImageFromWeb(url).Save(path, format);
        }

        public static void ImageFromWeb(string url, string proxy, string path, ImageFormat format)
        {
            ImageFromWeb(url, proxy).Save(path, format);
        }

        public static void DownloadFromWeb(string url, string filename)
        {
            try
            {
                WebClient wClient = new WebClient();
                wClient.DownloadFile(new Uri(url), filename);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void DownloadFromWeb(string url, string filename, string proxy)
        {
            try
            {
                WebClient wClient = new WebClient();
                WebProxy strProxy = new WebProxy(proxy, true);
                strProxy.Credentials = CredentialCache.DefaultCredentials;
                wClient.Proxy = strProxy;
                wClient.DownloadFile(new Uri(url), filename);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void DownloadFromWeb(string url, string filename, bool overwrite)
        {
            try
            {
                if (overwrite == true && System.IO.File.Exists(filename) == true)
                {
                    System.IO.File.Delete(filename);
                }
                if (System.IO.File.Exists(filename) == false)
                {
                    WebClient wClient = new WebClient();
                    wClient.DownloadFile(new Uri(url), filename);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void DownloadFromWeb(string url, string filename, string proxy, bool overwrite)
        {
            try
            {
                url = System.Web.HttpUtility.UrlDecode(url);
                if (overwrite == true)
                {
                    System.IO.File.Delete(filename);
                }
                if (System.IO.File.Exists(filename) == false)
                {
                    WebClient wClient = new WebClient();
                    WebProxy strProxy = new WebProxy(proxy, true);
                    strProxy.Credentials = CredentialCache.DefaultCredentials;
                    wClient.Proxy = strProxy;
                    wClient.DownloadFile(new Uri(url), filename);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static System.Data.DataSet readXMLfromURL(string url)
        {
            try
            {
                XmlTextReader xmlTextReader = new XmlTextReader(url);
                XmlDataDocument xdoc1 = new XmlDataDocument();
                xdoc1.DataSet.ReadXml(xmlTextReader, System.Data.XmlReadMode.InferSchema);
                return xdoc1.DataSet;
            }
            catch (Exception ex)
            { throw ex; }
        }


        /// <summary> 
        /// Gets the HTML links. 
        /// </summary> 
        /// <param name="html">The HTML.</param> 
        /// <returns></returns> 
        public static List<string> GetHtmlLinks(string html)
        {
            string linkPattern = "<a href=\"(.*?)\">(.*?)</a>";
            MatchCollection linkMatches = Regex.Matches(html, linkPattern, RegexOptions.Singleline);
            List<string> linkContents = new List<string>();
            foreach (Match match in linkMatches)
                linkContents.Add(match.Value);
            return linkContents;
        }


        /// <summary> 
        /// Gets the HTML Images. 
        /// </summary> 
        /// <param name="html">The HTML.</param> 
        /// <returns></returns> 
        public static List<string> GetHtmlImages(string html)
        {
            string linkPattern = "(?<=img\\s+src\\=[\x27\x22])(?<Url>[^\x27\x22]*)(?=[\x27\x22])";
            MatchCollection linkMatches = Regex.Matches(html, linkPattern, RegexOptions.Singleline);
            List<string> linkContents = new List<string>();
            foreach (Match match in linkMatches)
                linkContents.Add(match.Value);
            return linkContents;
        }

        /// <summary>
        /// Gets all Email addresses.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        public static List<string> GetHtmlEmail(string html)
        {
            List<string> result = new List<string>();
            System.Text.RegularExpressions.MatchCollection regexMatchCollection = System.Text.RegularExpressions.Regex.Matches(html, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            for (int i = 0; i < regexMatchCollection.Count; i++)
                if (!result.Contains(regexMatchCollection[i].Value))
                    result.Add(regexMatchCollection[i].Value);
            return result;
        }


        /// <summary>
        /// Removes the HTML Code.
        /// </summary>
        /// <param name="Text">The text.</param>
        /// <returns>The string without HTML Code</returns>
        public static string StripHTML(string inputString)
        {
            return Regex.Replace(inputString, "<.*?>", string.Empty);
        }


        /// <summary>
        /// Removes the HTML Comment Code.
        /// </summary>
        /// <param name="Text">The text.</param>
        /// <returns>The string without HTML Code</returns>
        public static string StripHTMLComments(string inputString)
        {
            return Regex.Replace(inputString, "\\<![ \\r\\n\\t]*(--([^\\-]|[\\r\\n]|-[^\\-])*--[ \\r\\n\\t]*)\\>", string.Empty, RegexOptions.Multiline );
        }


        

        public static void MakeScreenshotFromUrl(string url, string path)
        {
            WebBrowser wb = new WebBrowser();
            wb.ScrollBarsEnabled = false;
            wb.ScriptErrorsSuppressed = true;
            wb.Navigate(url);
            while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }

            wb.Width = wb.Document.Body.ScrollRectangle.Width;
            wb.Height = wb.Document.Body.ScrollRectangle.Height;

            Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
            wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
            wb.Dispose();

            bitmap.Save(@path, ImageFormat.Jpeg);
        }

        public static Bitmap MakeScreenshotFromUrl(string url)
        {
            WebBrowser wb = new WebBrowser();
            wb.ScrollBarsEnabled = false;
            wb.ScriptErrorsSuppressed = true;
            wb.Navigate(url);
            while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }

            wb.Width = wb.Document.Body.ScrollRectangle.Width;
            wb.Height = wb.Document.Body.ScrollRectangle.Height;

            Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
            wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
            wb.Dispose();
            return bitmap;
        }



    }

    public class cache
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="expire">Expire in Minutes</param>
        public static void addClientCache(int expire)
        {
            System.Web.HttpContext.Current.Response.Cache.VaryByParams["*"] = true;
            if (expire == 0)
            {
                System.Web.HttpContext.Current.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
                System.Web.HttpContext.Current.Response.Cache.SetMaxAge(TimeSpan.FromMinutes(expire));
                System.Web.HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddMinutes(expire));
                return;
            }
            
            System.Web.HttpContext.Current.Response.Cache.SetMaxAge(TimeSpan.FromMinutes(expire));
            System.Web.HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddMinutes(expire));
            System.Web.HttpContext.Current.Response.Cache.SetLastModified(DateTime.Now);
            System.Web.HttpContext.Current.Response.Cache.SetCacheability(System.Web.HttpCacheability.Private);

        }


        public static object addCache(string var, object value, int cachetime)
        {
            if (cachetime == 0)
            {
                return value;
            }
            try
            {
                if (value.ToString().StartsWith("Error:"))
                {
                    return value;
                }
            }
            catch { }

            System.Web.HttpContext.Current.Cache.Insert(var, value, null, DateTime.Now.AddMinutes(cachetime), System.Web.Caching.Cache.NoSlidingExpiration);
            return System.Web.HttpContext.Current.Cache[var];
        }

        public static object readCache(string var, int cachetime)
        {
            bool flush = false;
            if (System.Web.HttpContext.Current.Request.QueryString["flushcache"] != null)
            {
                if (System.Web.HttpContext.Current.Request.QueryString["flushcache"] == "true")
                {
                    flush = true;
                }

            }
            if (flush == true)
            {
                System.Web.HttpContext.Current.Cache.Remove(var);
            }
            return System.Web.HttpContext.Current.Cache[var];



        }

        public static string md5hash(string var)
        {
            return rowa.security.encrypt.md5hash(var);
        }

    }


    public static class urls
    {
        /// <summary>
        /// liefert den "Querystring" einer URL zurück
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="paramName"></param>
        /// <returns></returns>
        public static string ParameterValue(this Uri uri, string paramName)
        {
            if (uri != null && uri.Query != null && uri.Query.Length > 0 && uri.Query.ToLower().Contains(paramName.ToLower()))
            {
                Match m = Regex.Match(uri.Query, "^?" + paramName + "=([^&#]*)");
                if (m.Success) return System.Web.HttpUtility.UrlDecode(m.Value.Replace(paramName + "=", ""));
            }
            return "";
        }


        public static Int32 ParameterValueLength(this Uri uri)
        {
            if (uri != null && uri.Query != null && uri.Query.Length > 0 )
            {
                return uri.Query.Length;
            }
            return 0;
        }


        /// <summary>
        /// check status of an URL
        /// </summary>
        /// <param name="source">URL to check</param>
        /// <returns></returns>
        /// <remarks></remarks>

        public static string Check(string source)
        {
            string output = "";
            HttpWebRequest request;
            HttpWebResponse response = null;

            request = ((HttpWebRequest)(WebRequest.Create(source)));
            request.Timeout = 10000;
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            try
            {
                response = ((System.Net.HttpWebResponse)(request.GetResponse()));
                output = response.StatusCode.ToString();
                response.Close();
            }
            catch (Exception ex)
            {
                output = "Error: " + ex.Message;

            }
            
            return output;

        }

        
        /// <summary>
        /// check status of an URL
        /// </summary>
        /// <param name="source">URL to check</param>
        /// <param name="timeout">timeout in milliseconds</param>
        /// <returns></returns>
        /// <remarks></remarks>
        
        public static string Check(string source, int timeout)
        {
            string output = "";
            HttpWebRequest request;
            HttpWebResponse response = null;

            request = ((HttpWebRequest)(WebRequest.Create(source)));
            request.Timeout = timeout;
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            try
            {
                response = ((System.Net.HttpWebResponse)(request.GetResponse()));
                output = response.StatusCode.ToString();
                response.Close();
            }
            catch (Exception ex)
            {
                output =  "Error: " + ex.Message;

            }

            
            return output;
        }


        /// <summary>
        /// check status of an URL
        /// </summary>
        /// <param name="source">URL to check</param>
        /// <param name="cred">credentials to use</param>
        /// <param name="timeout">timeout in milliseconds</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static string Check(string source, System.Net.NetworkCredential cred, int timeout)
        {
            string output = "";
            HttpWebRequest request;
            HttpWebResponse response = null;
            request = ((HttpWebRequest)(WebRequest.Create(source)));
            request.Timeout = timeout;
            request.Credentials = cred;
            try
            {
                response = ((System.Net.HttpWebResponse)(request.GetResponse()));
                output = response.StatusCode.ToString();
                response.Close();
            }
            catch (Exception ex)
            {
                output = "<p>Error: " + ex.Message + "</p>";
            }
           
            return output;
        }

        public static string Check(string source, string proxyserver, int timeout)
        {
            string output = "";
            HttpWebRequest request;
            System.Net.WebProxy proxy = new System.Net.WebProxy(proxyserver, true);
            proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
            HttpWebResponse response = null;
            request = ((HttpWebRequest)(WebRequest.Create(source)));
            request.Timeout = timeout;
            request.Proxy = proxy;
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            try
            {
                response = ((System.Net.HttpWebResponse)(request.GetResponse()));
                output = response.StatusCode.ToString();
                response.Close();
            }
            catch (Exception ex)
            {
                output = "<p>Error: " + ex.Message + "</p>";
            }
            
            return output;
        }

        public static string Check(string source, string proxyserver, System.Net.NetworkCredential cred, int timeout)
        {
            string output = "";
            HttpWebRequest request;
            System.Net.WebProxy proxy = new System.Net.WebProxy(proxyserver, true);
            proxy.Credentials = cred;
            HttpWebResponse response = null;
            request = ((HttpWebRequest)(WebRequest.Create(source)));
            request.Timeout = timeout;
            request.Proxy = proxy;
            request.Credentials = cred;
            try
            {
                response = ((System.Net.HttpWebResponse)(request.GetResponse()));
                output = response.StatusCode.ToString();
                response.Close();
            }
            catch (Exception ex)
            {
                output = "<p>Error: " + ex.Message + "</p>";
            }
           
            return output;
        }

        /// <summary>
        /// Returns the responded HTTP headers of the given URL.
        /// </summary>
        /// <param name="Url">The adress.</param>
        /// <returns>List of headers</returns>
        public static Dictionary<string, string> GetHTTPResponseHeaders(string Url)
        {
            WebResponse ResponseObject = null;
            try
            {
                Dictionary<string, string> HeaderList = new Dictionary<string, string>();


                WebRequest WebRequestObject = HttpWebRequest.Create(Url);
                WebRequestObject.Credentials = System.Net.CredentialCache.DefaultCredentials;
                WebRequestObject.Proxy = WebRequest.DefaultWebProxy;
                WebRequestObject.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
                ResponseObject = WebRequestObject.GetResponse();

                foreach (string HeaderKey in ResponseObject.Headers)
                    HeaderList.Add(HeaderKey, ResponseObject.Headers[HeaderKey]);

                ResponseObject.Close();
                return HeaderList;

            }
            catch (Exception ex)
            {
                if (ResponseObject != null)
                {
                    ResponseObject.Close();
                }
                throw ex;
            }
        }

        /// <summary>
        /// Returns the responded HTTP headers of the given URL.
        /// </summary>
        /// <param name="Url">The adress.</param>
        /// <returns>List of headers</returns>
        public static Dictionary<string, string> GetHTTPResponseHeaders(string Url, int timeout)
        {
            WebResponse ResponseObject = null;
            try
            {
                Dictionary<string, string> HeaderList = new Dictionary<string, string>();


                WebRequest WebRequestObject = HttpWebRequest.Create(Url);
                WebRequestObject.Timeout = timeout * 1000;
                WebRequestObject.Credentials = System.Net.CredentialCache.DefaultCredentials;
                WebRequestObject.Proxy = WebRequest.DefaultWebProxy;
                WebRequestObject.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
                 ResponseObject = WebRequestObject.GetResponse();

                foreach (string HeaderKey in ResponseObject.Headers)
                    HeaderList.Add(HeaderKey, ResponseObject.Headers[HeaderKey]);

                ResponseObject.Close();
                return HeaderList;

            }
            catch (Exception ex)
            {
                if (ResponseObject != null)
                {
                    ResponseObject.Close();
                }
                throw ex;
            }
        }


        /// <summary>
        /// gibt einen Statuscode oder einen Fehler zurück
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string getStatusCode(string url)
        {
            return getStatusCode(url, 120);
        }


        /// <summary>
        /// gibt einen Statuscode oder einen Fehler zurück
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeout">in Sekunden</param>
        /// <returns></returns>
        public static string getStatusCode(string url, string proxyserver, int timeout)
        {
            try
            {
                HttpWebResponse HttpWResp = null;
                HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(url);

                try
                {
                    string status = "";
                    HttpWReq.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    HttpWReq.AllowAutoRedirect = false;
                    HttpWReq.Timeout = timeout * 1000;
                    

                    System.Net.WebProxy proxy = new System.Net.WebProxy(proxyserver, true);
                    proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
         

                    HttpWReq.Proxy = proxy;
                    HttpWReq.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    HttpWReq.Method = "head";
                    HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();

                    if (HttpWResp.ResponseUri.AbsoluteUri == url)
                    {
                        int code = (int)(HttpWResp.StatusCode);
                        status = code.ToString();
                    }
                    else
                    {
                        status = HttpWResp.ResponseUri.AbsoluteUri;
                    }

                    if (status.Contains("301"))
                    {
                        status = HttpWResp.GetResponseHeader("Location");
                        if (status.StartsWith("/"))
                        {
                            status = "http://" + HttpWReq.RequestUri.Host + status;
                        }
                        if (status == "")
                        {
                            status = HttpWResp.GetResponseHeader("Content-Location");
                            if (status == "")
                            {
                                status = "301 Redirect with unknown Destination!";
                            }
                        }
                    }
                    if (status.Contains("302"))
                    {
                        status = HttpWResp.GetResponseHeader("Location");
                        if (status.StartsWith("/"))
                        {
                            status = "http://" + HttpWReq.RequestUri.Host + status;
                        }
                        if (status == "")
                        {
                            status = HttpWResp.GetResponseHeader("Content-Location");
                            if (status == "")
                            {
                                status = "302 Redirect with unknown Destination!";
                            }
                        }
                    }

                    HttpWResp.Close();
                    return status;

                }
                catch (System.Web.HttpException ex)
                {
                    if (HttpWResp != null)
                    {
                        HttpWResp.Close();
                    }
                    return ex.Message;
                }
                catch (System.Net.WebException ex)
                {
                    if (HttpWResp != null)
                    {
                        HttpWResp.Close();
                    }
                    return ex.Message;
                }
                catch (Exception ex)
                {
                    if (HttpWResp != null)
                    {
                        HttpWResp.Close();
                    }
                    return ex.Message;
                }
            }
            catch (Exception exA)
            {
                return exA.Message;
            }


        }

        public static string getStatusCode(string url, int timeout, bool defaultproxy)
        {
            try
            {
                HttpWebResponse HttpWResp = null;
                HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(url);

                try
                {
                    string status = "";
                    HttpWReq.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    HttpWReq.AllowAutoRedirect = false;
                    HttpWReq.Timeout = timeout * 1000;
                    if (defaultproxy == true)
                    {
                        HttpWReq.Proxy = WebRequest.DefaultWebProxy;
                        HttpWReq.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    }
                    else
                    {
                        HttpWReq.Proxy = null;
                    }
                    HttpWReq.Method = "head";
                    HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();

                    if (HttpWResp.ResponseUri.AbsoluteUri == url)
                    {
                        int code = (int)(HttpWResp.StatusCode);
                        status = code.ToString();
                    }
                    else
                    {
                        status = HttpWResp.ResponseUri.AbsoluteUri;
                    }

                    if (status.Contains("301"))
                    {
                        status = HttpWResp.GetResponseHeader("Location");
                        if (status.StartsWith("/"))
                        {
                            status = "http://" + HttpWReq.RequestUri.Host + status;
                        }
                        if (status == "")
                        {
                            status = HttpWResp.GetResponseHeader("Content-Location");
                            if (status == "")
                            {
                                status = "301 Redirect with unknown Destination!";
                            }
                        }
                    }
                    if (status.Contains("302"))
                    {
                        status = HttpWResp.GetResponseHeader("Location");
                        if (status.StartsWith("/"))
                        {
                            status = "http://" + HttpWReq.RequestUri.Host + status;
                        }
                        if (status == "")
                        {
                            status = HttpWResp.GetResponseHeader("Content-Location");
                            if (status == "")
                            {
                                status = "302 Redirect with unknown Destination!";
                            }
                        }
                    }


                    HttpWResp.Close();
                    return status;

                }
                catch (System.Web.HttpException ex)
                {
                    if (HttpWResp != null)
                    {
                        HttpWResp.Close();
                    }
                    return ex.Message;
                }
                catch (System.Net.WebException ex)
                {
                    if (HttpWResp != null)
                    {
                        HttpWResp.Close();
                    }
                    return ex.Message;
                }
                catch (Exception ex)
                {
                    if (HttpWResp != null)
                    {
                        HttpWResp.Close();
                    }
                    return ex.Message;
                }
            }
            catch (Exception exA)
            {
                return exA.Message;
            }

        }


        /// <summary>
        /// gibt einen Statuscode oder einen Fehler zurück
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeout">in Sekunden</param>
        /// <returns></returns>
        public static string getStatusCode(string url, int timeout)
        {
            return getStatusCode(url, timeout, true);
        }

        public static string getRedirectUrl(string url, int timeout)
        {
            try
            {
                return rowa.web.urls.GetHTTPResponseHeaders(url, timeout)["Content-Location"];
            }
            catch (Exception ex)
            {
                return "Fehler:" + ex.Message;
            }
        }
        public static string getRedirectUrl(string url)
        {
            try
            {
                return rowa.web.urls.GetHTTPResponseHeaders(url)["Content-Location"];
            }
            catch (Exception ex)
            {
                return "Fehler:" + ex.Message;
            }
        }



    }

    public static class javascripts
    {
        public static string hashparameter()
        {
            string output = "";
            output = output + "function removeHashParam(variable) \n\r";
            output = output + "  { \n\r";
            output = output + "   output = null; \n\r";
            output = output + "   currentAnchor = window.location.hash; \n\r";
            output = output + "   try { \n\r";
            output = output + "   var params = currentAnchor.replace('#', '').split(','); \n\r";
            output = output + "   for (var i = 0; i < params.length; i++) { \n\r";
            output = output + "   if (params[i].split('=')[0] == variable) \n\r";
            output = output + "    { \n\r";
            output = output + "     window.location.hash = window.location.hash.replace(',' + params[i] , '').replace(params[i] + ',', '').replace(params[i], ''); \n\r";
            output = output + "    } \n\r";
            output = output + "   } \n\r";
            output = output + "   }  \n\r";
            output = output + "   catch (e)  \n\r";
            output = output + "   {} \n\r";
            output = output + "  } \n\r";


            output = output + "function readHashParam(variable) \n\r";
            output = output + "  { \n\r";
            output = output + "   output = null; \n\r";
            output = output + "   currentAnchor = window.location.hash; \n\r";
            output = output + "   try { \n\r";
            output = output + "     var params = currentAnchor.replace('#', '').split(','); \n\r";
            output = output + "     for (var i = 0; i < params.length; i++) { \n\r";
            output = output + "     if (params[i].split('=')[0] == variable) \n\r";
            output = output + "     { \n\r";
            output = output + "      if (params[i].split('=')[1] == '') \n\r";
            output = output + "      { \n\r";
            output = output + "       output = null; \n\r";
            output = output + "      } \n\r";
            output = output + "      else \n\r";
            output = output + "      { \n\r";
            output = output + "       output = params[i].split('=')[1]; \n\r";
            output = output + "      } \n\r";
            output = output + "     } \n\r";
            output = output + "     } \n\r";
            output = output + "    }  \n\r";
            output = output + "   catch (e)  \n\r";
            output = output + "    { return output; } \n\r";
            output = output + "     if (output != null)\n\r";
            output = output + "     {\n\r";
            //hier noch ein URL Encode / Decode einbauen!
            output = output + "     output = decodeURI(output);\n\r";
            //output = output + "     alert(output);\n\r";
            output = output + "     }\n\r";
            output = output + "   return output; \n\r";
            output = output + "   } \n\r";



            output = output + "function addHashParam(variable, value) \n\r";
            output = output + "  {\n\r";
            output = output + "   if (window.location.hash == '' || window.location.hash == '#') {\n\r";
            output = output + "   window.location.hash = variable + '=' + encodeURI(value);\n\r";
            output = output + "   } else {\n\r";
            output = output + "   // build new hash\n\r";
            output = output + "   window.location.hash += ',' + variable + '=' + encodeURI(value);\n\r";
            output = output + "   }\n\r";
            output = output + "  }\n\r";


            return output;
        }



    }

    public class google
    {
        private const UInt32 myConst = 0xE6359A60;
        private static void _Hashing(ref UInt32 a, ref UInt32 b, ref UInt32 c)
        {
            a -= b; a -= c; a ^= c >> 13;
            b -= c; b -= a; b ^= a << 8;
            c -= a; c -= b; c ^= b >> 13;
            a -= b; a -= c; a ^= c >> 12;
            b -= c; b -= a; b ^= a << 16;
            c -= a; c -= b; c ^= b >> 5;
            a -= b; a -= c; a ^= c >> 3;
            b -= c; b -= a; b ^= a << 10;
            c -= a; c -= b; c ^= b >> 15;
        }
        private static string PerfectHash(string theURL)
        {
            string url;
            url = string.Format("info:{0}", theURL);

            int length = url.Length;
            
            UInt32 a, b;
            UInt32 c = myConst;

            int k = 0;
            int len = length;

            a = b = 0x9E3779B9;

            while (len >= 12)
            {
                a += (UInt32)(url[k + 0] + (url[k + 1] << 8) + (url[k + 2] << 16) + (url[k + 3] << 24));
                b += (UInt32)(url[k + 4] + (url[k + 5] << 8) + (url[k + 6] << 16) + (url[k + 7] << 24));
                c += (UInt32)(url[k + 8] + (url[k + 9] << 8) + (url[k + 10] << 16) + (url[k + 11] << 24));
                _Hashing(ref a, ref b, ref c);
                k += 12;
                len -= 12;
            }
            c += (UInt32)length;
            switch (len) 
            {
                case 11: 
                    c += (UInt32)(url[k + 10] << 24); 
                    goto case 10;
                case 10: 
                    c += (UInt32)(url[k + 9] << 16); 
                    goto case 9;
                case 9: 
                    c += (UInt32)(url[k + 8] << 8); 
                    goto case 8;
                case 8: 
                    b += (UInt32)(url[k + 7] << 24); 
                    goto case 7;
                case 7: 
                    b += (UInt32)(url[k + 6] << 16); 
                    goto case 6;
                case 6: 
                    b += (UInt32)(url[k + 5] << 8); 
                    goto case 5;
                case 5: 
                    b += (UInt32)(url[k + 4]); 
                    goto case 4;
                case 4: 
                    a += (UInt32)(url[k + 3] << 24); 
                    goto case 3;
                case 3: 
                    a += (UInt32)(url[k + 2] << 16); 
                    goto case 2;
                case 2: 
                    a += (UInt32)(url[k + 1] << 8); 
                    goto case 1;
                case 1: 
                    a += (UInt32)(url[k + 0]); 
                    break;
                default: 
                    break;
            }
            
            _Hashing(ref a, ref b, ref c);

            return string.Format("6{0}", c);
        }
        public static int PageRank(string myURL)
        {
            string strDomainHash = PerfectHash(myURL);
            string myRequestURL = string.Format("http://toolbarqueries.google.com/search?client=navclient-auto&ch={0}&features=Rank&q=info:{1}", strDomainHash, myURL);

            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(myRequestURL);
                //System.Net.WebProxy proxy = new System.Net.WebProxy(proxyserver, true);
                //myRequest.Proxy = proxy;
                myRequest.Proxy = WebRequest.DefaultWebProxy;
                string myResponse = new StreamReader(myRequest.GetResponse().GetResponseStream()).ReadToEnd();
                if (myResponse.Length == 0)
                    return 0;
                else
                    return int.Parse(Regex.Match(myResponse, "Rank_1:[0-9]:([0-9]+)").Groups[1].Value);
            }
            catch (Exception)
            {
                return -1;
            }
        }
        public static int PageRank(string myURL, string proxyserver)
        {
            string strDomainHash = PerfectHash(myURL);
            string myRequestURL = string.Format("http://toolbarqueries.google.com/search?client=navclient-auto&ch={0}&features=Rank&q=info:{1}", strDomainHash, myURL);

            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(myRequestURL);
                System.Net.WebProxy proxy = new System.Net.WebProxy(proxyserver, true);
                myRequest.Proxy = proxy;
                myRequest.Proxy = WebRequest.DefaultWebProxy;
                string myResponse = new StreamReader(myRequest.GetResponse().GetResponseStream()).ReadToEnd();
                if (myResponse.Length == 0)
                    return 0;
                else
                    return int.Parse(Regex.Match(myResponse, "Rank_1:[0-9]:([0-9]+)").Groups[1].Value);
            }
            catch (Exception)
            {
                return -1;
            }
        }
    }

}


namespace rowa.xml
{
    using System.IO;
    using System.Net;
    using System.Data;
    using System.Collections;
    using System.Xml;
    using System.Data.SqlClient;
    public class get
    {
        /// <summary>
        /// returns a dataset from a remote xml source
        /// </summary>
        /// <param name="xmlSource">URL to XML source</param>
        /// <param name="timeout">timeout in milliseconds</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static System.Data.DataSet asDataset(string xmlSource, int timeout)
        {
            string xmlSourceStatus;
            StreamReader xmlStream;
            xmlStream = null;
            try
            {
                if (xmlSource.StartsWith("http"))
                {
                    xmlSourceStatus = rowa.web.urls.Check(xmlSource, timeout);
                    if (xmlSourceStatus.ToLower().Contains("ok"))
                    {
                        //mach(HTTP)
                        HttpWebRequest xmlRequest;
                        xmlRequest = ((HttpWebRequest)(WebRequest.Create(xmlSource)));
                        xmlRequest.Credentials = CredentialCache.DefaultCredentials;
                        xmlRequest.Timeout = timeout;
                        HttpWebResponse xmlResponse = ((HttpWebResponse)(xmlRequest.GetResponse()));
                        xmlStream = new StreamReader(xmlResponse.GetResponseStream());
                    }
                    else
                    {
                        throw new Exception("xmlSource " + xmlSource + " Status: " + xmlSourceStatus);
                    }
                }
                else
                {
                    // mach file
                    xmlStream = new StreamReader(xmlSource);
                }

                System.Data.DataSet xmlDS = new System.Data.DataSet();
                xmlDS.ReadXml(xmlStream);
                return xmlDS;

            }
            catch (Exception ex)
            {
                throw ex;

            }
        }



  
    }
    public class transform
    {

           public static string  escapeXml(string input) 
           {
               string output = "";
        
        output = input.Replace("&", "&amp;");
        output = output.Replace("'", "&apos;");
        output = output.Replace("\"", "&quot;");
        output = output.Replace(">", "&gt;");
        output = output.Replace("<", "&lt;");
        output = output.Replace("&fnof;", "&#402;");
        output = output.Replace("&Alpha;", "&#913;");
        output = output.Replace("&Beta;", "&#914;");
        output = output.Replace("&Gamma;", "&#915;");
        output = output.Replace("&Delta;", "&#402;");
        output = output.Replace("&Epsilon;", "&#917;");
        output = output.Replace("&Zeta;", "&#918;");
        output = output.Replace("&Eta;", "&#919;");
        output = output.Replace("&Theta;", "&#920;");
        output = output.Replace("&Iota;", "&#921;");
        output = output.Replace("&Kappa;", "&#922;");
        output = output.Replace("&Lambda;", "&#923;");
        output = output.Replace("&Mu;", "&#924;");
        output = output.Replace("&Nu;", "&#925;");
        output = output.Replace("&Xi;", "&#926;");
        output = output.Replace("&Omicron;", "&#927;");
        output = output.Replace("&Pi;", "&#928;");
        output = output.Replace("&Rho;", "&#929;");
        output = output.Replace("&Sigma;", "&#931;");
        output = output.Replace("&Tau;", "&#932;");
        output = output.Replace("&Upsilon;", "&#933;");
        output = output.Replace("&Phi;", "&#934;");
        output = output.Replace("&Chi;", "&#935;");
        output = output.Replace("&Psi;", "&#936;");
        output = output.Replace("&Omega;", "&#937;");
        output = output.Replace("&alpha;", "&#945;");
        output = output.Replace("&beta;", "&#946;");
        output = output.Replace("&gamma;", "&#947;");
        output = output.Replace("&delta;", "&#948;");
        output = output.Replace("&epsilon;", "&#949;");
        output = output.Replace("&zeta;", "&#950;");
        output = output.Replace("&eta;", "&#951;");
        output = output.Replace("&theta;", "&#952;");
        output = output.Replace("&iota;", "&#953;");
        output = output.Replace("&kappa;", "&#954;");
        output = output.Replace("&lambda;", "&#955;");
        output = output.Replace("&mu;", "&#956;");
        output = output.Replace("&nu;", "&#957;");
        output = output.Replace("&xi;", "&#958;");
        output = output.Replace("&omicron;", "&#959;");
        output = output.Replace("&pi;", "&#960;");
        output = output.Replace("&rho;", "&#961;");
        output = output.Replace("&sigmaf;", "&#962;");
        output = output.Replace("&sigma;", "&#963;");
        output = output.Replace("&tau;", "&#964;");
        output = output.Replace("&upsilon;", "&#965;");
        output = output.Replace("&phi;", "&#966;");
        output = output.Replace("&chi;", "&#967;");
        output = output.Replace("&psi;", "&#968;");
        output = output.Replace("&omega;", "&#969;");
        output = output.Replace("&thetasym;", "&#977;");
        output = output.Replace("&upsih;", "&#978;");
        output = output.Replace("&piv;", "&#982;");
        return output.Trim();
           }



        public static string XmlAsString(XmlReader xmlReader)
        {
            string output = "";
            output = new System.Xml.XPath.XPathDocument(xmlReader).CreateNavigator().OuterXml;
            return output;
        }


            public static string XmlToJSON(DataSet ds)
            {
                try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    StringWriter stringWriter = new StringWriter();
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
                    ds.WriteXml(xmlTextWriter, XmlWriteMode.IgnoreSchema);
                    string contentAsXmlString = stringWriter.ToString();
                    xmlDoc.LoadXml(contentAsXmlString);


                    StringBuilder sbJSON = new StringBuilder();
                    sbJSON.Append("{ ");
                    XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
                    sbJSON.Append("}");
                    return sbJSON.ToString();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            public static string XmlToJSON(DataSet ds, bool metadaten)
            {
                try
                {
                    if (metadaten == true)
                    {
                        try
                        {
                        DataTable dt = new DataTable("meta");
                        ds.Tables.Add(dt);
                        DataColumn dc;
                        dc = new DataColumn("rowcount");
                        dt.Columns.Add(dc);
                        }
                        catch 
                        { }

                        ds.Tables["meta"].Clear();
                        DataRow row = ds.Tables["meta"].NewRow();
                        row["rowcount"] = ds.Tables[0].Rows.Count;
                        ds.Tables["meta"].Rows.Add(row);
                    }

                    XmlDocument xmlDoc = new XmlDocument();
                    StringWriter stringWriter = new StringWriter();
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
                    ds.WriteXml(xmlTextWriter, XmlWriteMode.IgnoreSchema);
                    string contentAsXmlString = stringWriter.ToString();
                    xmlDoc.LoadXml(contentAsXmlString);


                    StringBuilder sbJSON = new StringBuilder();
                    sbJSON.Append("{ ");
                    XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
                    sbJSON.Append("}");
                    return sbJSON.ToString();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
               
            }



            public static string XmlToJSON(string xmlstring, bool metadaten)
            {
                try
                {
                    data.datasets rDS = new data.datasets();
                    DataSet ds = rDS.getDataset(xmlstring);

                    if (metadaten == true)
                    {
                        DataTable dt = new DataTable("meta");
                        ds.Tables.Add(dt);
                        DataColumn dc;
                        dc = new DataColumn("rowcount");
                        dt.Columns.Add(dc);

                        DataRow row = ds.Tables["meta"].NewRow();
                        row["rowcount"] = ds.Tables[0].Rows.Count;
                        ds.Tables["meta"].Rows.Add(row);
                    }

                    XmlDocument xmlDoc = new XmlDocument();
                    StringWriter stringWriter = new StringWriter();
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
                    ds.WriteXml(xmlTextWriter, XmlWriteMode.IgnoreSchema);
                    string contentAsXmlString = stringWriter.ToString();
                    xmlDoc.LoadXml(contentAsXmlString);


                    StringBuilder sbJSON = new StringBuilder();
                    sbJSON.Append("{ ");
                    XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
                    sbJSON.Append("}");
                    return sbJSON.ToString();
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }





            public static string XmlToJSON(XmlDocument xmlDoc)
            {
                try
                {
                    StringBuilder sbJSON = new StringBuilder();
                    sbJSON.Append("{ ");
                    XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
                    sbJSON.Append("}");
                    return sbJSON.ToString();
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }

            //  XmlToJSONnode:  Output an XmlElement, possibly as part of a higher array
            private static void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName)
            {
                if (showNodeName)
                    sbJSON.Append("\"" + SafeJSON(node.Name) + "\": ");
                sbJSON.Append("{");
                // Build a sorted list of key-value pairs
                //  where   key is case-sensitive nodeName
                //          value is an ArrayList of string or XmlElement
                //  so that we know whether the nodeName is an array or not.
                System.Collections.SortedList childNodeNames = new System.Collections.SortedList();

                //  Add in all node attributes
                if (node.Attributes != null)
                    foreach (XmlAttribute attr in node.Attributes)
                        StoreChildNode(childNodeNames, attr.Name, attr.InnerText);

                //  Add in all nodes
                foreach (XmlNode cnode in node.ChildNodes)
                {
                    if (cnode is XmlText)
                        StoreChildNode(childNodeNames, "value", cnode.InnerText);
                    else if (cnode is XmlElement)
                        StoreChildNode(childNodeNames, cnode.Name, cnode);
                }

                // Now output all stored info
                foreach (string childname in childNodeNames.Keys)
                {
                    ArrayList alChild = (ArrayList)childNodeNames[childname];
                    if (alChild.Count == 1)
                        OutputNode(childname, alChild[0], sbJSON, true);
                    else
                    {
                        sbJSON.Append(" \"" + SafeJSON(childname) + "\": [ ");
                        foreach (object Child in alChild)
                            OutputNode(childname, Child, sbJSON, false);
                        sbJSON.Remove(sbJSON.Length - 2, 2);
                        sbJSON.Append(" ], ");
                    }
                }
                sbJSON.Remove(sbJSON.Length - 2, 2);
                sbJSON.Append(" }");
            }

            //  StoreChildNode: Store data associated with each nodeName
            //                  so that we know whether the nodeName is an array or not.
            private static void StoreChildNode(System.Collections.SortedList childNodeNames, string nodeName, object nodeValue)
            {
                // Pre-process contraction of XmlElement-s
                if (nodeValue is XmlElement)
                {
                    // Convert  <aa></aa> into "aa":null
                    //          <aa>xx</aa> into "aa":"xx"
                    XmlNode cnode = (XmlNode)nodeValue;
                    if (cnode.Attributes.Count == 0)
                    {
                        XmlNodeList children = cnode.ChildNodes;
                        if (children.Count == 0)
                            nodeValue = null;
                        else if (children.Count == 1 && (children[0] is XmlText))
                            nodeValue = ((XmlText)(children[0])).InnerText;
                    }
                }
                // Add nodeValue to ArrayList associated with each nodeName
                // If nodeName doesn't exist then add it
                object oValuesAL = childNodeNames[nodeName];
                ArrayList ValuesAL;
                if (oValuesAL == null)
                {
                    ValuesAL = new ArrayList();
                    childNodeNames[nodeName] = ValuesAL;
                }
                else
                    ValuesAL = (ArrayList)oValuesAL;
                ValuesAL.Add(nodeValue);
            }

            private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)
            {
                try
                {
                    if (alChild == null)
                    {
                        if (showNodeName)
                            sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
                        sbJSON.Append("null");
                    }
                    else if (alChild is string)
                    {
                        if (showNodeName)
                            sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
                        string sChild = (string)alChild;
                        sChild = sChild.Trim();
                        sbJSON.Append("\"" + SafeJSON(sChild) + "\"");
                    }
                    else
                        XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);
                    sbJSON.Append(", ");

                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            // Make a string safe for JSON
            private static string SafeJSON(string sIn)
            {
                StringBuilder sbOut = new StringBuilder(sIn.Length);
                foreach (char ch in sIn)
                {
                    if (Char.IsControl(ch) || ch == '\'')
                    {
                        int ich = (int)ch;
                        sbOut.Append(@"\u" + ich.ToString("x4"));
                        continue;
                    }
                    else if (ch == '\"' || ch == '\\' || ch == '/')
                    {
                        sbOut.Append('\\');
                    }
                    sbOut.Append(ch);
                }
                return sbOut.ToString();
            }


            public static string doRender(DataSet ds, Stream xsl)
            {
                string xml = ds.GetXml();
                StringReader rdr = new StringReader(xml);


                System.Xml.XmlTextReader oXSLR = new System.Xml.XmlTextReader(xsl);
                try
                {
                    System.IO.StringWriter osW = new System.IO.StringWriter();

                    System.Xml.XPath.XPathDocument oXPath = new System.Xml.XPath.XPathDocument(rdr);
                    System.Xml.Xsl.XslCompiledTransform rs = new System.Xml.Xsl.XslCompiledTransform();
                    System.Xml.Xsl.XslCompiledTransform oXSLT = new System.Xml.Xsl.XslCompiledTransform();
                    // load xsl file
                    oXSLT.Load(oXSLR, System.Xml.Xsl.XsltSettings.TrustedXslt, new System.Xml.XmlUrlResolver());
                    // transform it into something better ;-)
                    oXSLT.Transform(oXPath, null, osW);
                    // return transformed string
                    return osW.ToString();
                }
                catch (Exception ex)
                {
                    try { oXSLR.Close(); }
                    catch { }

                    return ex.ToString();
                }
            }


        public static string doRender(Stream xml, Stream xsl)
        {
            System.Xml.XmlTextReader oXR = new System.Xml.XmlTextReader(xml);
            System.Xml.XmlTextReader oXSLR = new System.Xml.XmlTextReader(xsl);
            try
            {
                System.IO.StringWriter osW = new System.IO.StringWriter();
                System.Xml.XPath.XPathDocument oXPath = new System.Xml.XPath.XPathDocument(oXR);
                System.Xml.Xsl.XslCompiledTransform rs = new System.Xml.Xsl.XslCompiledTransform();
                System.Xml.Xsl.XslCompiledTransform oXSLT = new System.Xml.Xsl.XslCompiledTransform();
                // load xsl file
                oXSLT.Load(oXSLR, System.Xml.Xsl.XsltSettings.TrustedXslt, new System.Xml.XmlUrlResolver());
                // transform it into something better ;-)
                oXSLT.Transform(oXPath, null, osW);
                // return transformed string
                string output = osW.ToString();
                oXSLR.Close();
                osW.Close();
                oXR.Close();
                return output;
            }
            catch (Exception ex)
            {
                try { oXSLR.Close(); }
                catch { }
                try { oXR.Close(); }
                catch { }
                return ex.ToString() ;
            }
        }
        public static string renderXMLContent(System.Data.DataSet ds, string xslSource, int timeout)
        {
            string output = "";
            if (!(output == ""))
            {
                return output;
            }
            string xslSourceStatus;
            StreamReader xslStream;
            xslStream = null;
            try
            {
                if (xslSource.StartsWith("http"))
                {
                    xslSourceStatus = rowa.web.urls.Check(xslSource, timeout);
                    if (xslSourceStatus.ToLower().Contains("ok"))
                    {
                        // mach HTTP
                        HttpWebRequest xslRequest;
                        // request.Credentials = New Net.NetworkCredential("user", "pass")
                        xslRequest = ((HttpWebRequest)(WebRequest.Create(xslSource)));
                        xslRequest.Timeout = timeout;
                        xslRequest.Credentials = CredentialCache.DefaultCredentials;
                        HttpWebResponse xslResponse = ((HttpWebResponse)(xslRequest.GetResponse()));
                        xslStream = new StreamReader(xslResponse.GetResponseStream());
                    }
                    else
                    {
                        output = xslSourceStatus;
                    }
                }
                else
                {
                    // mach file
                    xslStream = new StreamReader(xslSource);
                }
                output = doRender(ds, xslStream.BaseStream);

            }
            catch (Exception ex)
            {
                output = "Error:<p>" + ex.ToString() + "<br />XSL:" + xslSource + "<br/>XML:" + ds.GetXml() + "</p>";
            }
            finally
            {
                try
                {
                    xslStream.Close();
                }
                catch { }
            }
            return output;
        }


        public static string renderXMLContent(string xmlSource, string xslSource, int timeout)
        {
            string output = "";
            if (!(output == ""))
            {
                return output;
            }
            string xmlSourceStatus;
            string xslSourceStatus;
            StreamReader xmlStream;
            StreamReader xslStream;
            xmlStream = null;
            xslStream = null;
            try
            {
                if (xmlSource.StartsWith("http"))
                {
                    xmlSourceStatus = rowa.web.urls.Check(xmlSource, timeout);
                    if (xmlSourceStatus.ToLower().Contains("ok"))
                    {
                        // mach HTTP
                        HttpWebRequest xmlRequest;

                        xmlRequest = ((HttpWebRequest)(WebRequest.Create(xmlSource)));
                        xmlRequest.Timeout = timeout;
                        xmlRequest.Credentials = CredentialCache.DefaultCredentials;
                        HttpWebResponse xmlResponse = ((HttpWebResponse)(xmlRequest.GetResponse()));
                        xmlStream = new StreamReader(xmlResponse.GetResponseStream());

                    }
                    else
                    {
                        output = xmlSourceStatus;
                    }
                }
                else
                {
                    // mach file
                    xmlStream = new StreamReader(xmlSource);
                }

                if (xslSource.StartsWith("http"))
                {
                    xslSourceStatus = rowa.web.urls.Check(xslSource, timeout);
                    if (xslSourceStatus.ToLower().Contains("ok"))
                    {
                        // mach HTTP
                        HttpWebRequest xslRequest;
                        // request.Credentials = New Net.NetworkCredential("user", "pass")
                        xslRequest = ((HttpWebRequest)(WebRequest.Create(xslSource)));
                        xslRequest.Timeout = timeout;
                        xslRequest.Credentials = CredentialCache.DefaultCredentials;
                        HttpWebResponse xslResponse = ((HttpWebResponse)(xslRequest.GetResponse()));
                        xslStream = new StreamReader(xslResponse.GetResponseStream());
                    }
                    else
                    {
                        output =  xslSourceStatus;
                    }
                }
                else
                {
                    // mach file
                    xslStream = new StreamReader(xslSource);
                }
                output =  doRender(xmlStream.BaseStream, xslStream.BaseStream);

            }
            catch (Exception ex)
            {
                output =  "Error:<p>" + ex.ToString() + "<br />XML:" + xmlSource + "<br />XSL:" + xslSource + "</p>";
            }
            finally
            {
                try
                {
                    xmlStream.Close();
                    xslStream.Close();
                }
                catch { }
            }
            return output;
        }
    }
}
namespace rowa.office
{
    using System.Data;
    using System.Data.OleDb;
    using System.Xml;
    public class excel
    {
        public static DataTable getAllSheets(string filename)
        {
            try
            {
                OleDbConnection conn = new OleDbConnection();

                if (Environment.OSVersion.Version.Major < 6)
                {
                    conn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0;";
                }
                else
                {
                    conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties=Excel 12.0;";
                }
                conn.Open();
                DataTable dtWorksheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[]{null, null});
                conn.Close();
                return dtWorksheets;
            }
            catch (Exception ex)
            {
                throw ex;
            }
                
        }
        public static DataTable getAllColumnHeaders(string filename, string sheet)
        {
            try
            {
                OleDbConnection conn = new OleDbConnection();
                if (Environment.OSVersion.Version.Major < 6)
                {
                    conn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0;";
                }
                else
                {
                    conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties=Excel 12.0;";
                }
                conn.Open();
                OleDbDataAdapter da = new OleDbDataAdapter();
                da.SelectCommand = new OleDbCommand("select top 1 * from [" + sheet + "]", conn);
                OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
                DataTable dt = new DataTable("ColumnHeaders");
                da.Fill(dt);
                conn.Close();

                DataTable dtout = new DataTable("ColumnHeaders");
                DataColumn dcout = new DataColumn("columns");
                dtout.Columns.Add(dcout);
                foreach (DataColumn dc in dt.Columns)
                {
                    DataRow newrow;
                    newrow = dtout.NewRow();
                    newrow["columns"] = dc.ColumnName;
                    dtout.Rows.Add(newrow);    
                }
                return dtout;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static DataTable getExcelsheet(string filename, string sheet)
        {
            try
            {
                OleDbConnection conn = new OleDbConnection();
                if (Environment.OSVersion.Version.Major < 6)
                {
                    conn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0;";
                }
                else
                {
                    conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties=Excel 12.0;";
                }
                conn.Open();
                OleDbDataAdapter da = new OleDbDataAdapter();
                
                da.SelectCommand = new OleDbCommand("select * from [" + sheet + "]", conn);
                OleDbCommandBuilder cb = new OleDbCommandBuilder(da);

                

                DataTable dt = new DataTable("ColumnHeaders");
                da.Fill(dt);
                conn.Close();
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static void ExportDataTableToWorksheet(DataTable dataSource, string fileName)
        {
            ExportDataTableToWorksheet(dataSource, fileName, false);
        }


        public static void ExportDataTableToWorksheet(DataSet  dataSource, string fileName, Boolean withHeaderColumn)
        {
            // XML-Schreiber erzeugen
            XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8);

            // Ausgabedatei für bessere Lesbarkeit formatieren (einrücken etc.)
            writer.Formatting = Formatting.Indented;

            // <?xml version="1.0"?>
            writer.WriteStartDocument();

            // <?mso-application progid="Excel.Sheet"?>
            writer.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");

            // <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet >"
            writer.WriteStartElement("Workbook", "urn:schemas-microsoft-com:office:spreadsheet");

            // Definition der Namensräume schreiben 
            writer.WriteAttributeString("xmlns", "o", null, "urn:schemas-microsoft-com:office:office");
            writer.WriteAttributeString("xmlns", "x", null, "urn:schemas-microsoft-com:office:excel");
            writer.WriteAttributeString("xmlns", "ss", null, "urn:schemas-microsoft-com:office:spreadsheet");
            writer.WriteAttributeString("xmlns", "html", null, "http://www.w3.org/TR/REC-html40");

            // <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
            writer.WriteStartElement("DocumentProperties", "urn:schemas-microsoft-com:office:office");

            // Dokumenteingeschaften schreiben
            writer.WriteElementString("Author", Environment.UserName);
            writer.WriteElementString("LastAuthor", Environment.UserName);
            writer.WriteElementString("Created", DateTime.Now.ToString("u") + "Z");
            writer.WriteElementString("Company", "Unknown");
            writer.WriteElementString("Version", "11.8122");

            // </DocumentProperties>
            writer.WriteEndElement();

            // <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
            writer.WriteStartElement("ExcelWorkbook", "urn:schemas-microsoft-com:office:excel");

            // Arbeitsmappen-Einstellungen schreiben
            writer.WriteElementString("WindowHeight", "13170");
            writer.WriteElementString("WindowWidth", "17580");
            writer.WriteElementString("WindowTopX", "120");
            writer.WriteElementString("WindowTopY", "60");
            writer.WriteElementString("ProtectStructure", "False");
            writer.WriteElementString("ProtectWindows", "False");

            // </ExcelWorkbook>
            writer.WriteEndElement();

            // <Styles>
            writer.WriteStartElement("Styles");

            // <Style ss:ID="Default" ss:Name="Normal">
            writer.WriteStartElement("Style");
            writer.WriteAttributeString("ss", "ID", null, "Default");
            writer.WriteAttributeString("ss", "Name", null, "Normal");

            // <Alignment ss:Vertical="Bottom"/>
            writer.WriteStartElement("Alignment");
            writer.WriteAttributeString("ss", "Vertical", null, "Bottom");
            writer.WriteEndElement();

            // Verbleibende Sytle-Eigenschaften leer schreiben
            writer.WriteElementString("Borders", null);
            writer.WriteElementString("Font", null);
            writer.WriteElementString("Interior", null);
            writer.WriteElementString("NumberFormat", null);
            writer.WriteElementString("Protection", null);

            // </Style>
            writer.WriteEndElement();


            writer.WriteStartElement("Style");
            writer.WriteAttributeString("ss", "ID", null, "s62");
            writer.WriteAttributeString("ss", "Name", null, "Hyperlink");
            writer.WriteStartElement("Font");
            writer.WriteAttributeString("ss", "FontName", null, "Arial");
            writer.WriteAttributeString("ss", "Color", null, "#0000FF");
            writer.WriteAttributeString("ss", "Underline", null, "Single");
            writer.WriteEndElement();
            writer.WriteEndElement();

            writer.WriteStartElement("Style");
            writer.WriteAttributeString("ss", "ID", null, "s63");
            writer.WriteAttributeString("ss", "Parent", null, "s62");
            writer.WriteStartElement("Alignment");
            writer.WriteAttributeString("ss", "Vertical", null, "Bottom");
            writer.WriteEndElement();
            writer.WriteEndElement();

            // </Styles>
            writer.WriteEndElement();

            foreach (DataTable dt in dataSource.Tables)
            {
                ExportDataTableToWorkSheetAddTable(dt, ref writer, ref withHeaderColumn);
            }

            // </Worksheet>
            writer.WriteEndElement();

            // </Workbook>
            writer.WriteEndElement();

            // Datei auf Festplatte schreiben
            writer.Flush();
            writer.Close();
        }
        public static void ExportDataTableToWorksheet(DataTable dataSource, string fileName, Boolean withHeaderColumn)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add(dataSource.Copy());
            ExportDataTableToWorksheet(ds, fileName, withHeaderColumn);
        }


        public static void ExportDataTableToWorksheet(DataTable dataSource, System.Web.HttpContext context, string displayname)
        {
            ExportDataTableToWorksheet(dataSource, context, displayname, false);
        }
        public static void ExportDataTableToWorksheet(DataSet dataSource, System.Web.HttpContext context, string displayname)
        {
            ExportDataTableToWorksheet(dataSource, context, displayname, false);
        }

        public static void ExportDataTableToWorksheet(DataSet  dataSource, System.Web.HttpContext context, string displayname, Boolean withHeaderColumn)
        {
            context.Response.Clear();
            context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + displayname);
            context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            context.Response.ContentType = "application/ms-excel";


            // XML-Schreiber erzeugen
            XmlTextWriter writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8);

            // Ausgabedatei für bessere Lesbarkeit formatieren (einrücken etc.)
            writer.Formatting = Formatting.Indented;

            // <?xml version="1.0"?>
            writer.WriteStartDocument();

            // <?mso-application progid="Excel.Sheet"?>
            writer.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");

            // <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet >"
            writer.WriteStartElement("Workbook", "urn:schemas-microsoft-com:office:spreadsheet");

            // Definition der Namensräume schreiben 
            writer.WriteAttributeString("xmlns", "o", null, "urn:schemas-microsoft-com:office:office");
            writer.WriteAttributeString("xmlns", "x", null, "urn:schemas-microsoft-com:office:excel");
            writer.WriteAttributeString("xmlns", "ss", null, "urn:schemas-microsoft-com:office:spreadsheet");
            writer.WriteAttributeString("xmlns", "html", null, "http://www.w3.org/TR/REC-html40");

            // <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
            writer.WriteStartElement("DocumentProperties", "urn:schemas-microsoft-com:office:office");

            // Dokumenteingeschaften schreiben
            writer.WriteElementString("Author", Environment.UserName);
            writer.WriteElementString("LastAuthor", Environment.UserName);
            writer.WriteElementString("Created", DateTime.Now.ToString("u") + "Z");
            writer.WriteElementString("Company", "Unknown");
            writer.WriteElementString("Version", "11.8122");

            // </DocumentProperties>
            writer.WriteEndElement();

            // <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
            writer.WriteStartElement("ExcelWorkbook", "urn:schemas-microsoft-com:office:excel");

            // Arbeitsmappen-Einstellungen schreiben
            writer.WriteElementString("WindowHeight", "13170");
            writer.WriteElementString("WindowWidth", "17580");
            writer.WriteElementString("WindowTopX", "120");
            writer.WriteElementString("WindowTopY", "60");
            writer.WriteElementString("ProtectStructure", "False");
            writer.WriteElementString("ProtectWindows", "False");

            // </ExcelWorkbook>
            writer.WriteEndElement();

            // <Styles>
            writer.WriteStartElement("Styles");

            // <Style ss:ID="Default" ss:Name="Normal">
            writer.WriteStartElement("Style");
            writer.WriteAttributeString("ss", "ID", null, "Default");
            writer.WriteAttributeString("ss", "Name", null, "Normal");

            // <Alignment ss:Vertical="Bottom"/>
            writer.WriteStartElement("Alignment");
            writer.WriteAttributeString("ss", "Vertical", null, "Bottom");
            writer.WriteEndElement();

            // Verbleibende Sytle-Eigenschaften leer schreiben
            writer.WriteElementString("Borders", null);
            writer.WriteElementString("Font", null);
            writer.WriteElementString("Interior", null);
            writer.WriteElementString("NumberFormat", null);
            writer.WriteElementString("Protection", null);

            // </Style>
            writer.WriteEndElement();



            writer.WriteStartElement("Style");
            writer.WriteAttributeString("ss", "ID", null, "s62");
            writer.WriteAttributeString("ss", "Name", null, "Hyperlink");
            writer.WriteStartElement("Font");
            writer.WriteAttributeString("ss", "FontName", null, "Arial");
            writer.WriteAttributeString("ss", "Color", null, "#0000FF");
            writer.WriteAttributeString("ss", "Underline", null, "Single");
            writer.WriteEndElement();
            writer.WriteEndElement();

            writer.WriteStartElement("Style");
            writer.WriteAttributeString("ss", "ID", null, "s63");
            writer.WriteAttributeString("ss", "Parent", null, "s62");
            writer.WriteStartElement("Alignment");
            writer.WriteAttributeString("ss", "Vertical", null, "Bottom");
            writer.WriteEndElement();
            writer.WriteEndElement();

            // </Styles>
            writer.WriteEndElement();

            foreach (DataTable dt in dataSource.Tables)
            {
                ExportDataTableToWorkSheetAddTable(dt, ref writer, ref withHeaderColumn);
            }

            // </Workbook>
            writer.WriteEndElement();

            writer.Flush();
            writer.Close();
        }
        public static void ExportDataTableToWorksheet(DataTable dataSource, System.Web.HttpContext context, string displayname, Boolean withHeaderColumn)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add(dataSource.Copy());
            ExportDataTableToWorksheet(ds, context, displayname, withHeaderColumn);
        }

        public static System.IO.Stream ExportDataTableToWorksheet(DataSet dataSource, Boolean withHeaderColumn)
        {
            System.IO.Stream w = new System.IO.MemoryStream();
            // XML-Schreiber erzeugen
            XmlTextWriter writer = new XmlTextWriter(w, Encoding.UTF8);

            // Ausgabedatei für bessere Lesbarkeit formatieren (einrücken etc.)
            writer.Formatting = Formatting.Indented;

            // <?xml version="1.0"?>
            writer.WriteStartDocument();

            // <?mso-application progid="Excel.Sheet"?>
            writer.WriteProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");

            // <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet >"
            writer.WriteStartElement("Workbook", "urn:schemas-microsoft-com:office:spreadsheet");

            // Definition der Namensräume schreiben 
            writer.WriteAttributeString("xmlns", "o", null, "urn:schemas-microsoft-com:office:office");
            writer.WriteAttributeString("xmlns", "x", null, "urn:schemas-microsoft-com:office:excel");
            writer.WriteAttributeString("xmlns", "ss", null, "urn:schemas-microsoft-com:office:spreadsheet");
            writer.WriteAttributeString("xmlns", "html", null, "http://www.w3.org/TR/REC-html40");

            // <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
            writer.WriteStartElement("DocumentProperties", "urn:schemas-microsoft-com:office:office");

            // Dokumenteingeschaften schreiben
            writer.WriteElementString("Author", Environment.UserName);
            writer.WriteElementString("LastAuthor", Environment.UserName);
            writer.WriteElementString("Created", DateTime.Now.ToString("u") + "Z");
            writer.WriteElementString("Company", "Unknown");
            writer.WriteElementString("Version", "11.8122");

            // </DocumentProperties>
            writer.WriteEndElement();

            // <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
            writer.WriteStartElement("ExcelWorkbook", "urn:schemas-microsoft-com:office:excel");

            // Arbeitsmappen-Einstellungen schreiben
            writer.WriteElementString("WindowHeight", "13170");
            writer.WriteElementString("WindowWidth", "17580");
            writer.WriteElementString("WindowTopX", "120");
            writer.WriteElementString("WindowTopY", "60");
            writer.WriteElementString("ProtectStructure", "False");
            writer.WriteElementString("ProtectWindows", "False");

            // </ExcelWorkbook>
            writer.WriteEndElement();

            // <Styles>
            writer.WriteStartElement("Styles");

            // <Style ss:ID="Default" ss:Name="Normal">
            writer.WriteStartElement("Style");
            writer.WriteAttributeString("ss", "ID", null, "Default");
            writer.WriteAttributeString("ss", "Name", null, "Normal");

            // <Alignment ss:Vertical="Bottom"/>
            writer.WriteStartElement("Alignment");
            writer.WriteAttributeString("ss", "Vertical", null, "Bottom");
            writer.WriteEndElement();

            // Verbleibende Sytle-Eigenschaften leer schreiben
            writer.WriteElementString("Borders", null);
            writer.WriteElementString("Font", null);
            writer.WriteElementString("Interior", null);
            writer.WriteElementString("NumberFormat", null);
            writer.WriteElementString("Protection", null);

            // </Style>
            writer.WriteEndElement();

            writer.WriteStartElement("Style");
            writer.WriteAttributeString("ss", "ID", null, "s62");
            writer.WriteAttributeString("ss", "Name", null, "Hyperlink");
            writer.WriteStartElement("Font");
            writer.WriteAttributeString("ss", "FontName", null, "Arial");
            writer.WriteAttributeString("ss", "Color", null, "#0000FF");
            writer.WriteAttributeString("ss", "Underline", null, "Single");
            writer.WriteEndElement();
            writer.WriteEndElement();

            writer.WriteStartElement("Style");
            writer.WriteAttributeString("ss", "ID", null, "s63");
            writer.WriteAttributeString("ss", "Parent", null, "s62");
            writer.WriteStartElement("Alignment");
            writer.WriteAttributeString("ss", "Vertical", null, "Bottom");
            writer.WriteEndElement();
            writer.WriteEndElement();

            // </Styles>
            writer.WriteEndElement();


            foreach (DataTable dt in dataSource.Tables)
            {
                ExportDataTableToWorkSheetAddTable(dt.Copy(), ref writer, ref withHeaderColumn);
            }
            



            // </Workbook>
            writer.WriteEndElement();

            writer.Flush();
            writer.Close();
            return w;
        }
        public static System.IO.Stream ExportDataTableToWorksheet(DataTable dataSource, Boolean withHeaderColumn)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add(dataSource.Copy());
            return ExportDataTableToWorksheet(ds, withHeaderColumn);
        }

        /// <summary>
        /// Erzeugt aus einer DataTable ein Excel-XML-Dokument mit SpreadsheetML.
        /// </summary>        
        /// <param name="dataSource">Datenquelle, die in Excel exportiert werden soll</param>
        /// <param name="fileName">Dateiname der Ausgabe-XML-Datei</param>
        public static System.IO.Stream ExportDataTableToWorksheet(DataTable dataSource)
        {
            return ExportDataTableToWorksheet(dataSource, false);
        }
        public static System.IO.Stream ExportDataTableToWorksheet(DataSet dataSource)
        {
            return ExportDataTableToWorksheet(dataSource, false);
        }

        /// <summary>
        /// Hilfsfunktion, fügt nur die Tabelle dem Excelsheet hinzu.
        /// </summary>
        /// <param name="dataSource"></param>
        /// <param name="writer"></param>
        /// <param name="withHeaderColumn"></param>
        private static void ExportDataTableToWorkSheetAddTable(DataTable dataSource, ref XmlTextWriter writer, ref Boolean withHeaderColumn)
        {

            // <Worksheet ss:Name="xxx">
            writer.WriteStartElement("Worksheet");
            writer.WriteAttributeString("ss", "Name", null, dataSource.TableName);


                  // <Table ss:ExpandedColumnCount="2" ss:ExpandedRowCount="3" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="60">
            writer.WriteStartElement("Table");
            writer.WriteAttributeString("ss", "ExpandedColumnCount", null, dataSource.Columns.Count.ToString());
            int rows = dataSource.Rows.Count;
            if (withHeaderColumn == true)
            {
                rows = rows + 1;
            }
            writer.WriteAttributeString("ss", "ExpandedRowCount", null, rows.ToString());
            writer.WriteAttributeString("x", "FullColumns", null, "1");
            writer.WriteAttributeString("x", "FullRows", null, "1");
            writer.WriteAttributeString("ss", "DefaultColumnWidth", null, "60");

            if (withHeaderColumn == true)
            {
                writer.WriteStartElement("Row");

                // Alle Zellen der aktuellen Zeile durchlaufen
                foreach (DataColumn dc in dataSource.Columns)
                {
                    // <Cell>
                    writer.WriteStartElement("Cell");
                 
                    // <Data ss:Type="String">xxx</Data>
                    writer.WriteStartElement("Data");
                    writer.WriteAttributeString("ss", "Type", null, "String");

                    // Zelleninhakt schreiben
                    try { writer.WriteValue(dc.ColumnName); }
                    catch { }
                    // </Data>
                    writer.WriteEndElement();

                    // </Cell>
                    writer.WriteEndElement();
                }
                // </Row>
                writer.WriteEndElement();

            }



            // Alle Zeilen der Datenquelle durchlaufen
            foreach (DataRow row in dataSource.Rows)
            {
                // <Row>
                writer.WriteStartElement("Row");

                // Alle Zellen der aktuellen Zeile durchlaufen
                foreach (object cellValue in row.ItemArray)
                {
                    // <Cell>
                    writer.WriteStartElement("Cell");
                    try
                    {
                        if (cellValue.ToString().Trim().ToLower().StartsWith("http"))
                        {
                            writer.WriteAttributeString("ss", "StyleID", null, "s63");
                            writer.WriteAttributeString("ss", "HRef", null, cellValue.ToString().Trim());
                        }
                    }
                    catch { }

                    // <Data ss:Type="String">xxx</Data>

                    try
                    {
                        if (cellValue.ToString().Length > 0)
                        {
                            writer.WriteStartElement("Data");
                            writer.WriteAttributeString("ss", "Type", null, "String");

                            // Zelleninhakt schreiben
                            try { writer.WriteValue(cellValue); }
                            catch { }
                            // </Data>
                            writer.WriteEndElement();
                        }

                    }
                    catch(Exception ex)
                    {

                    }




                    // </Cell>
                    writer.WriteEndElement();
                }
                // </Row>
                writer.WriteEndElement();
            }
            // </Table>
            writer.WriteEndElement();

            // <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
            writer.WriteStartElement("WorksheetOptions", "urn:schemas-microsoft-com:office:excel");

            // Seiteneinstellungen schreiben
            writer.WriteStartElement("PageSetup");
            writer.WriteStartElement("Header");
            writer.WriteAttributeString("x", "Margin", null, "0.4921259845");
            writer.WriteEndElement();
            writer.WriteStartElement("Footer");
            writer.WriteAttributeString("x", "Margin", null, "0.4921259845");
            writer.WriteEndElement();
            writer.WriteStartElement("PageMargins");
            writer.WriteAttributeString("x", "Bottom", null, "0.984251969");
            writer.WriteAttributeString("x", "Left", null, "0.78740157499999996");
            writer.WriteAttributeString("x", "Right", null, "0.78740157499999996");
            writer.WriteAttributeString("x", "Top", null, "0.984251969");
            writer.WriteEndElement();
            writer.WriteEndElement();

            // <Selected/>
            writer.WriteElementString("Selected", null);

            // <Panes>
            writer.WriteStartElement("Panes");

            // <Pane>
            writer.WriteStartElement("Pane");

            // Bereichseigenschaften schreiben
            writer.WriteElementString("Number", "1");
            writer.WriteElementString("ActiveRow", "1");
            writer.WriteElementString("ActiveCol", "1");

            // </Pane>
            writer.WriteEndElement();

            // </Panes>
            writer.WriteEndElement();

            // <ProtectObjects>False</ProtectObjects>
            writer.WriteElementString("ProtectObjects", "False");

            // <ProtectScenarios>False</ProtectScenarios>
            writer.WriteElementString("ProtectScenarios", "False");

            // </WorksheetOptions>
            writer.WriteEndElement();

            // </Worksheet>
            writer.WriteEndElement();
        
        }



    }
}
namespace rowa.text
    {
        using System.Text.RegularExpressions;
        public class counter
        {
            /// <summary>
            /// Zählt die Wörter in einem Text
            /// </summary>
            /// <param name="str">der zu analysierende Text</param>
            /// <param name="regexStr">das gesuchte Wort</param>
            /// <returns></returns>
            public static int WordsInText(string str, string regexStr)
                {
                Regex regex = new Regex(regexStr);
                return regex.Matches(str).Count;
                }
        }

        public class compare
        {
            public static Boolean isSame(string val1, string val2)
            {
                //string[] parts1 = val1.Split(new char[] { '\u00A0', }, StringSplitOptions.RemoveEmptyEntries);
                //val1 = string.Join(string.Empty, parts1);

                //string[] parts2 = val2.Split(new char[] { '\u00A0', }, StringSplitOptions.RemoveEmptyEntries);
                //val2 = string.Join(string.Empty, parts2);

                //if (string.Compare(val1, val2, true) == 0)
                //{
                //    return true;
                //}
                //else
                //{
                //    return false;
                //}






                val1 = val1.Replace(Environment.NewLine, null);
                val1 = val1.Replace("\r", null);
                val1 = val1.Replace("\n", null);

                val2 = val2.Replace(Environment.NewLine, null);
                val2 = val2.Replace("\r", null);
                val2 = val2.Replace("\n", null);

                if (val1.Trim().ToLower() == val2.Trim().ToLower())
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
        }

    }
namespace rowa.grafik
{
    using System.Drawing;
    using System.Drawing.Imaging;
    public class charts
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt">Vorraussetzung Spalte 1 String, Spalte 2 Wert</param>
        /// <param name="pfad"></param>
        /// <param name="height"></param>
        /// <param name="width"></param>
        public static void drawChart(System.Data.DataTable dt, string pfad, int height, int width, string bgcolor, string valuecolor, string titel, bool showvalues)
        {
            PixelFormat objFormat = new PixelFormat();
            objFormat = PixelFormat.Format24bppRgb;
            Bitmap objBitmap = new Bitmap(width, height, objFormat);
            Graphics gr = Graphics.FromImage(objBitmap);

            SolidBrush backcolor = new SolidBrush(ColorTranslator.FromHtml("#" + bgcolor));
            gr.FillRectangle(backcolor, 0, 0, width, height);

            int Balkenbreite = 0;
            Balkenbreite = width / ((dt.Rows.Count * 2) + 1) * 2;

            int StartBreite = 0;

            decimal maxValue = 0;
            foreach (System.Data.DataRow dx in dt.Rows)
            {
                if ((Convert.ToInt32(dx[1])) > maxValue)
                {
                    maxValue = Convert.ToDecimal(dx[1]);
                }
            }

            decimal faktor = 1;
            if ((maxValue) > height)
            {
                faktor = height / (maxValue);
            }
            foreach (System.Data.DataRow dx in dt.Rows)
            {
                dx[1] = Convert.ToDecimal(dx[1]) * faktor;
            }

            Font ft = new Font("Arial", 8, FontStyle.Regular, GraphicsUnit.Pixel);
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            gr.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            SolidBrush fontcolor = new SolidBrush(ColorTranslator.FromHtml("#000000"));
            SolidBrush balkencolor = new SolidBrush(ColorTranslator.FromHtml("#" + valuecolor));


            foreach (System.Data.DataRow dx in dt.Rows)
            {
                int wert = Convert.ToInt32(rowa.calculation.math.CommercialRound(Convert.ToDecimal(dx[1]), 0));
                StartBreite = StartBreite + Balkenbreite;

                //if (showvalues)
                //{
                //System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();
                //mat.Translate(height, width);   // Die Mittelpunkt zum Nullpunkt verschieben
                //mat.Rotate(-90);
                //gr.Transform = mat;
                //gr.DrawString(Convert.ToString(rowa.calculation.math.CommercialRound(Convert.ToDecimal(dx[1]) / faktor, 2)), ft, fontcolor, 0, StartBreite);
                //mat.Reset();
                //gr.Transform = mat;
                //}


                gr.FillRectangle(balkencolor, StartBreite, height - wert, Balkenbreite / 2, wert);



            }

            if (titel.Length > 0)
            {
                gr.DrawString(titel, ft, fontcolor, 1, 1);
            }

            objBitmap.Save(pfad);
        }
    }
    public class images
    {
        public static bool convertImage(string source, string destination, ImageFormat format)
        {
            if (System.IO.File.Exists(source))
            {
                Image imTemp;
                imTemp = Image.FromFile(source);
                imTemp.Save(destination, format);
                return true;
            }
            else
            { return false; }
           
        }

      
        public class EXIFManager
        {
            public EXIFManager()
            {

            }

            public ImageMetadata ReadEXIFMetadata(string filepath)
            {
                Image image = Image.FromFile(filepath);
                PropertyItem[] imagePropertyItems = image.PropertyItems;
                ImageMetadata imageMetadata = new ImageMetadata();

                foreach (PropertyItem pi in imagePropertyItems)
                {
                    switch ((EXIFProperty)pi.Id)
                    {
                        case EXIFProperty.Title:
                            imageMetadata.Title = Encoding.UTF8.GetString(pi.Value);
                            break;
                        case EXIFProperty.Author:
                            imageMetadata.Author = Encoding.UTF8.GetString(pi.Value);
                            break;
                        case EXIFProperty.Keywords:
                            imageMetadata.Keywords = Encoding.UTF8.GetString(pi.Value);
                            break;
                        case EXIFProperty.Comments:
                            imageMetadata.Comments = Encoding.UTF8.GetString(pi.Value);
                            break;
                        default:
                            break;
                    }
                }

                return imageMetadata;
            }

            public void SaveEXIFMetadata(Image image, ImageMetadata metadata, string filepath)
            {
                SaveEXIFMetadataProperty(image, EXIFProperty.Title, metadata.Title, filepath);
                SaveEXIFMetadataProperty(image, EXIFProperty.Author, metadata.Author, filepath);
                SaveEXIFMetadataProperty(image, EXIFProperty.Keywords, metadata.Keywords, filepath);
                SaveEXIFMetadataProperty(image, EXIFProperty.Comments, metadata.Comments, filepath);
            }

            private void SaveEXIFMetadataProperty(Image image, EXIFProperty property,
                                                  string propertyValue, string filepath)
            {
                PropertyItem propertyItem = CreatePropertyItem();
                propertyItem.Id = (int)property;
                // Type=1 means Array of Bytes.  
                propertyItem.Type = 2;
                propertyItem.Len = propertyValue.Length;
                propertyItem.Value = Encoding.UTF8.GetBytes(propertyValue);

                image.SetPropertyItem(propertyItem);
                image.Save(filepath);
            }

            private PropertyItem CreatePropertyItem()
            {
                System.Reflection.ConstructorInfo ci = typeof(PropertyItem).GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, new Type[] { }, null);
                return (PropertyItem)ci.Invoke(null);
            }
        }

        public enum EXIFProperty
        {
            Title = 40091,
            Author = 40093,
            Keywords = 40094,
            Comments = 40092
        }

        public class ImageMetadata
        {
            private string _title = string.Empty;
            private string _author = string.Empty;
            private string _keywords = string.Empty;
            private string _comments = string.Empty;

            public ImageMetadata()
            {
                this._title = string.Empty;
                this._author = string.Empty;
                this._keywords = string.Empty;
                this._comments = string.Empty;
            }

            public ImageMetadata(string title, string author, string keywords, string comments)
            {
                this._title = title;
                this._author = author;
                this._keywords = keywords;
                this._comments = comments;
            }

            public string Title
            {
                get
                {
                    return this._title;
                }

                set
                {
                    this._title = value;
                }
            }

            public string Author
            {
                get
                {
                    return this._author;
                }

                set
                {
                    this._author = value;
                }
            }

            public string Keywords
            {
                get
                {
                    return this._keywords;
                }

                set
                {
                    this._keywords = value;
                }
            }

            public string Comments
            {
                get
                {
                    return this._comments;
                }

                set
                {
                    this._comments = value;
                }
            }
        }  

    }

}
namespace rowa.Astronomy.AstronomyLib
{
    /// <summary>
    /// simplified moonphases
    /// </summary>
    public enum MoonPhases
    {
        /// <summary>
        /// Newmoon phase.
        /// </summary>
        newmoon = 0,
        /// <summary>
        /// Waxing crescent moon phase.
        /// </summary>
        waxingcrescent = 1,
        /// <summary>
        /// First quarter phase.
        /// </summary>
        firstquarter = 2,
        /// <summary>
        /// Waxing gibbous moon phase.
        /// </summary>
        waxinggibbous = 3,
        /// <summary>
        /// Fullmoon phase.
        /// </summary>
        fullmoon = 4,
        /// <summary>
        /// Waning gibbous moon phase.
        /// </summary>
        waninggibbous = 5,
        /// <summary>
        /// Last quarter phase.
        /// </summary>
        lastquarter = 6,
        /// <summary>
        /// Waning crescent moon phase.
        /// </summary>
        waningcrescent = 7
    }
}
namespace rowa.Astronomy
{
    using rowa.Astronomy.AstronomyLib;
    /// <summary>
    /// Represents the simplified moonphases of a given date.
    /// </summary>
    public class Moon
    {
        /// <summary>
        /// The moonphase of the given date.
        /// </summary>
        public MoonPhases Phase;

        /// <summary>
        /// Initializes a new instance of the <see cref="Moon"/> class.
        /// </summary>
        /// <param name="year">The year.</param>
        /// <param name="day">The day.</param>
        /// <param name="hour">The hour.</param>
        public Moon(int year, int month, int day)
        {
            var YY = year - (Int32)((12 - month) / 10);
            var MM = month + 9;
            if (MM >= 12) { MM = MM - 12; }
            var K1 = (Int32)(365.25 * (YY + 4712));
            var K2 = (Int32)(30.6 * MM + .5);
            var K3 = (Int32)((Int32)((YY / 100) + 49) * .75) - 38;
            var J = K1 + K2 + day + 59;
            if (J > 2299160) { J = J - K3; }
            var V = (J - 2451550.1) / 29.530588853;
            V = V - (Int32)(V);
            if (V < 0) { V = V + 1; }
            var AG = V * 29.53;
            if ((AG > 27.6849270496875) || (AG <= 1.8456618033125))
            {
                Phase = MoonPhases.newmoon;
            }
            else if ((AG > 1.8456618033125) && (AG <= 5.5369854099375))
            {
                Phase = MoonPhases.waxingcrescent;
            }
            else if ((AG > 5.5369854099375) && (AG <= 9.2283090165625))
            {
                Phase = MoonPhases.firstquarter;
            }
            else if ((AG > 9.2283090165625) && (AG <= 12.9196326231875))
            {
                Phase = MoonPhases.waxinggibbous;
            }
            else if ((AG > 12.9196326231875) && (AG <= 16.6109562298125))
            {
                Phase = MoonPhases.fullmoon;
            }
            else if ((AG > 16.6109562298125) && (AG <= 20.3022798364375))
            {
                Phase = MoonPhases.waninggibbous;
            }
            else if ((AG > 20.3022798364375) && (AG <= 23.9936034430625))
            {
                Phase = MoonPhases.lastquarter;
            }
            else if ((AG > 23.9936034430625) && (AG <= 27.6849270496875))
            {
                Phase = MoonPhases.waningcrescent;
            }
            else
            {
                Phase = MoonPhases.fullmoon;
            }
        }
    }
    /// <summary>
    /// A class that provides sun informations of a given day on a given location
    /// represented by latitude and longtitude.
    /// </summary>
    public class Sun
    {
        #region ctor

        /// <summary>
        /// Initializes a new instance of the <see cref="Sun"/> class.
        /// </summary>
        /// <param name="Latitude">The latitude.</param>
        /// <param name="Longtitude">The longtitude.</param>
        /// <param name="year">The year.</param>
        /// <param name="month">The month.</param>
        /// <param name="day">The day.</param>
        public Sun(double Latitude, double Longtitude, int year, int month, int day)
        {
            var PI = Math.PI;
            var DR = PI / 180;
            var RD = 1 / DR;
            var B5 = Latitude;
            var L5 = Longtitude;
            var H = 0;    // timezone UTC
            var Now = DateTime.Now;
            var M = month;
            var D = day;
            B5 = DR * B5;
            var N = (Int32)(275 * M / 9) - 2 * (Int32)((M + 9) / 12) + D - 30;
            var L0 = 4.8771 + .0172 * (N + .5 - L5 / 360);
            var C = .03342 * Math.Sin(L0 + 1.345);
            var C2 = RD * (Math.Atan(Math.Tan(L0 + C)) - Math.Atan(.9175 * Math.Tan(L0 + C)) - C);
            var SD = .3978 * Math.Sin(L0 + C);
            var CD = Math.Sqrt(1 - SD * SD);
            var SC = (SD * Math.Sin(B5) + .0145) / (Math.Cos(B5) * CD);

            if (Math.Abs(SC) <= 1)
            {
                // calculate sunrise 
                var C3 = RD * Math.Atan(SC / Math.Sqrt(1 - SC * SC));
                var R1 = 6 - H - (L5 + C2 + C3) / 15;
                var HR = (Int32)(R1);
                var MR = (Int32)((R1 - HR) * 60);
                Sunrise = new DateTime(year, month, day, HR, MR, 0);
                // calculate sunset
                var S1 = 18 - H - (L5 + C2 - C3) / 15;
                var HS = (Int32)(S1);
                var MS = (Int32)((S1 - HS) * 60);
                Sunset = new DateTime(year, month, day, HS, MS, 0);
            }
            else
            {
                if (SC > 1)
                {
                    // sun is up all day ...
                    // Set Sunset to be in the future ...
                    Sunset = new DateTime(Now.Year + 1, Now.Month, Now.Day, Now.Hour, Now.Minute, Now.Second);
                    // Set Sunrise to be in the past ...
                    Sunrise = new DateTime(Now.Year - 1, Now.Month, Now.Day, Now.Hour, Now.Minute - 1, Now.Second);
                }
                if (SC < -1)
                {
                    // sun is down all day ...
                    // Set Sunrise and Sunset to be in the future ...
                    Sunrise = new DateTime(Now.Year + 1, Now.Month, Now.Day, Now.Hour, Now.Minute, Now.Second);
                    Sunset = new DateTime(Now.Year + 1, Now.Month, Now.Day, Now.Hour, Now.Minute, Now.Second);
                }
            }
        }

        #endregion
    
        #region fields

        /// <summary>
        /// DateTime representation of the sunrise-timestamp of a given day on a given location.
        /// </summary>
        public DateTime Sunrise;

        /// <summary>
        /// DateTime representation of the sunset-timestamp of a given day on a given location.
        /// </summary>
        public DateTime Sunset;


        #endregion
    }
}
namespace rowa.Geography
{
    /// <summary>
    /// Eine Geokoordinate aus Längen- und Breitengrad
    /// </summary>
    public class GeoCoordinate
    {
        private GeoPoint m_Latitude;
        private GeoPoint m_Longitude;

        public const double EARTHRADIUSKM = 6378.137;
        public const double NMFACTOR = 1.852216;
        public const double EARTHRADIUSNM = EARTHRADIUSKM / NMFACTOR;
        public const double EARTHPLATTUNG = 1.0 / 298.257223563;

        #region Constructor
        /// <summary>
        /// Erstellt eine neue Geokoordinate mit den angegebenen Koordinaten
        /// </summary>
        /// <param name="latitude">Breitengrad in Dezimalgrad</param>
        /// <param name="longitude">Längengrad in Dezimalgrad</param>
        public GeoCoordinate(double latitude, double longitude)
        {
            m_Latitude = new GeoPoint(latitude < 0 ? "S" : "N", latitude);
            m_Longitude = new GeoPoint(longitude < 0 ? "E" : "W", longitude);
        }

        /// <summary>
        /// Erstellt eine neue Geokoordinate aus den angegebenen GeoPoints
        /// </summary>
        /// <param name="latitude">Breitengrad</param>
        /// <param name="longitude">Längengrad</param>
        public GeoCoordinate(GeoPoint latitude, GeoPoint longitude)
        {
            if (latitude.Indicator != "N" && latitude.Indicator != "S")
                throw new ArgumentException("Latitude must be N or S!");

            if (longitude.Indicator != "W" && longitude.Indicator != "E")
                throw new ArgumentException("Longitude must be W or E!");

            m_Latitude = latitude;
            m_Longitude = longitude;
        }
        #endregion

        #region Static Methods
        /// <summary>
        /// Berechnet die Länge des Orthodroms zwischen zwei Punkten
        /// </summary>
        /// <remarks>Versucht eine Berechnung nach WGS84</remarks>
        /// <param name="c1">Erster Punkt</param>
        /// <param name="c2">Zweiter Punkt</param>
        /// <returns>Entfernung in Kilometern</returns>
        public static double DistanceKM(GeoCoordinate c1, GeoCoordinate c2)
        {
            double dist = 0.0;

            try
            {
                dist = CalcDistanceWGS84(c1, c2, EARTHRADIUSKM);
            }
            catch
            {
                dist = CalcDistance(c1, c2) * EARTHRADIUSKM;
            }

            return dist;
        }

        /// <summary>
        /// Berechnet die Länge des Orthodroms zwischen zwei Punkten
        /// </summary>
        /// <remarks>Versucht eine Berechnung nach WGS84</remarks>
        /// <param name="c1">Erster Punkt</param>
        /// <param name="c2">Zweiter Punkt</param>
        /// <returns>Entfernung in nautischen Meilen</returns>
        public static double DistanceNM(GeoCoordinate c1, GeoCoordinate c2)
        {
            double dist = 0.0;

            try
            {
                dist = CalcDistanceWGS84(c1, c2, EARTHRADIUSKM) / NMFACTOR;
            }
            catch
            {
                dist = CalcDistance(c1, c2) * EARTHRADIUSNM;
            }

            return dist;
        }

        /// <summary>
        /// Berechnet den Kurswinkel zwischen zwei Punkten
        /// </summary>
        /// <param name="c1">Erster Punkt</param>
        /// <param name="c2">Zweiter Punkt</param>
        /// <returns>Kurswinkel in Grad (Rechtsweisend)</returns>
        public static double CourseAngle(GeoCoordinate c1, GeoCoordinate c2)
        {
            double lat1 = GetRAD(c1.m_Latitude.DecGrad);
            double lat2 = GetRAD(c2.m_Latitude.DecGrad);

            double alpha = GetDEG(Math.Acos(
                (Math.Sin(lat2) - Math.Sin(lat1) * Math.Cos(CalcDistance(c1, c2))) /
                (Math.Cos(lat1) * Math.Sin(CalcDistance(c1, c2)))));

            if (lat1 > lat2)
                return 360.0 - alpha;
            else
                return alpha;
        }

        #region Static Helper
        private static double CalcDistance(GeoCoordinate c1, GeoCoordinate c2)
        {
            double lat1 = GetRAD(c1.m_Latitude.DecGrad);
            double lat2 = GetRAD(c2.m_Latitude.DecGrad);

            double lon1 = GetRAD(c1.m_Longitude.DecGrad);
            double lon2 = GetRAD(c2.m_Longitude.DecGrad);

            return Math.Acos(
                Math.Sin(lat1) * Math.Sin(lat2) +
                Math.Cos(lat1) * Math.Cos(lat2) * Math.Cos(lon2 - lon1));
        }

        private static double CalcDistanceWGS84(GeoCoordinate c1, GeoCoordinate c2, double earthRadius)
        {
            double lat1 = c1.m_Latitude.DecGrad;
            double lat2 = c2.m_Latitude.DecGrad;

            double lon1 = c1.m_Longitude.DecGrad;
            double lon2 = c2.m_Longitude.DecGrad;

            double F = GetRAD((lat1 + lat2) / 2.0);
            double G = GetRAD((lat1 - lat2) / 2.0);
            double l = GetRAD((lon1 - lon2) / 2.0);

            double S = (Math.Pow(Math.Sin(G), 2) * Math.Pow(Math.Cos(l), 2)) +
                (Math.Pow(Math.Cos(F), 2) * Math.Pow(Math.Sin(l), 2));
            double C = (Math.Pow(Math.Cos(G), 2) * Math.Pow(Math.Cos(l), 2)) +
                (Math.Pow(Math.Sin(F), 2) * Math.Pow(Math.Sin(l), 2));

            double w = Math.Atan(Math.Sqrt(S / C));

            double D = 2 * w * earthRadius;

            double R = (Math.Sqrt(S * C)) / w;
            double H1 = (3 * R - 1) / (2 * C);
            double H2 = (3 * R + 1) / (2 * S);

            return D * (
                1 + EARTHPLATTUNG * H1 * Math.Pow(Math.Sin(F), 2) * Math.Pow(Math.Cos(G), 2) -
                EARTHPLATTUNG * H2 * Math.Pow(Math.Cos(F), 2) * Math.Pow(Math.Sin(G), 2));
        }

        private static double GetRAD(double deg)
        {
            return deg / 180.0 * Math.PI;
        }

        private static double GetDEG(double rad)
        {
            return rad * 180.0 / Math.PI;
        }
        #endregion
        #endregion

        #region Class Methods
        /// <summary>
        /// Berechnet die Länge des Orthodroms zwischen diesem und einem anderen Punkt
        /// </summary>
        /// <remarks>Versucht eine Berechnung nach WGS84</remarks>
        /// <param name="c1">Erster Punkt</param>
        /// <returns>Entfernung in Kilometern</returns>
        /// <seealso cref="GeoCoordinate.DistanceKM"/>
        public double DistanceKM(GeoCoordinate c1)
        {
            return GeoCoordinate.DistanceKM(this, c1);
        }

        /// <summary>
        /// Berechnet die Länge des Orthodroms zwischen diesem und einem anderen Punkt
        /// </summary>
        /// <remarks>Versucht eine Berechnung nach WGS84</remarks>
        /// <param name="c1">Erster Punkt</param>
        /// <returns>Entfernung in nautischen Meilen</returns>
        /// <seealso cref="GeoCoordinate.DistanceNM"/>
        public double DistanceNM(GeoCoordinate c1)
        {
            return GeoCoordinate.DistanceNM(this, c1);
        }

        /// <summary>
        /// Berechnet den Kurswinkel zwischen diesem und einem anderen Punkt
        /// </summary>
        /// <param name="c1">Erster Punkt</param>
        /// <returns>Kurswinkel in Grad (Rechtsweisend)</returns>
        /// <seealso cref="GeoCoordinate.CourseAngle" />
        public double CourseAngle(GeoCoordinate c1)
        {
            return GeoCoordinate.CourseAngle(this, c1);
        }
        #endregion

        #region Overridden Methods
        public override string ToString()
        {
            return m_Latitude.ToString() + " " + m_Longitude.ToString();
        }
        #endregion

        /// <summary>
        /// Ein Koordinatenpunkt in Grad, Minuten und Sekunden
        /// </summary>
        public class GeoPoint
        {
            #region Fields
            private string m_Indicator;
            private double m_Decimal;
            #endregion

            #region Properties
            /// <summary>
            /// Dezimale Repräsentation des Punktes
            /// </summary>
            public double DecGrad
            {
                get
                {
                    return m_Decimal;
                }
            }

            /// <summary>
            /// Indikator, ob N/S bzw. W/E
            /// </summary>
            public string Indicator
            {
                get
                {
                    return m_Indicator;
                }
            }

            /// <summary>
            /// Die vollen Grad des Koordinatenpunktes
            /// </summary>
            public int Grad
            {
                get
                {
                    return Convert.ToInt32(Math.Floor(Math.Abs(m_Decimal)));
                }
            }

            /// <summary>
            /// Die Minuten des Koordinatenpunktes
            /// </summary>
            public int Minute
            {
                get
                {
                    double calc = Math.Abs(m_Decimal);
                    calc -= Math.Floor(calc);

                    return Convert.ToInt32(Math.Floor(calc * 60.0));
                }
            }

            /// <summary>
            /// Die Dezimalsekunden des Koordinatenpunktes
            /// </summary>
            public double Sekunde
            {
                get
                {
                    double calc = Math.Abs(m_Decimal);
                    calc -= Math.Floor(calc);
                    calc -= (Math.Floor(calc * 60.0) / 60.0);

                    return Math.Round(calc * 3600.0, 2);
                }
            }
            #endregion

            #region Constructors
            /// <summary>
            /// Erstellt einen Koordinatenpunkt auf der angegebenen Halbkugel aus Dezimalgrad
            /// </summary>
            /// <param name="indicator">N/S oder W/E</param>
            /// <param name="decGrad">Koordinate in Dezimalgrad</param>
            public GeoPoint(string indicator, double decGrad)
            {
                m_Indicator = indicator;
                m_Decimal = Math.Abs(decGrad);

                switch (indicator)
                {
                    case "S":
                    case "E":
                        m_Decimal *= -1.0;
                        break;
                }
            }

            /// <summary>
            /// Erstellt einen Koordinatenpunkt auf der angebenen Halbkugel aus einer Gradangabe
            /// </summary>
            /// <param name="indicator">N/S oder W/E</param>
            /// <param name="grad">Die vollen Grad</param>
            /// <param name="minute">Minuten</param>
            /// <param name="sekunde">Dezimalsekunden</param>
            public GeoPoint(string indicator, int grad, int minute, double sekunde)
            {
                InitByGrad(indicator, grad, minute, sekunde);
            }

            /// <summary>
            /// Erstellt einen Koordinatenpunkt aus einem String
            /// </summary>
            /// <param name="point">
            /// <para>String in folgendem Format:</para>
            /// <para>&lt;IND&gt;&lt;GRAD&gt;[MINUTE][SEKUNDEN]</para>
            /// <para>IND: N/S/W/E (ein Zeichen)</para>
            /// <para>GRAD: Grad (2 stellig)</para>
            /// <para>MINUTE: Minuten(2 stellig)</para>
            /// <para>SEKUNDE: Sekunden(2...n stellig, ohne Komma)</para>
            /// <para></para><para>Beispiel: N6044122323</para>
            /// </param>
            public GeoPoint(string point)
            {
                string indicator = "";
                int grad = 0;
                int minute = 0;
                double sekunde = 0.0;

                if (point[0] != 'N' && point[0] != 'S' && point[0] != 'W' && point[0] != 'E')
                    throw new ArgumentException("String must start with N,S,W or E");

                indicator = point.Substring(0, 1);

                if (point.Length == 3)
                    grad = Int32.Parse(point.Substring(1, 2));

                if (point.Length == 5)
                {
                    grad = Int32.Parse(point.Substring(1, 2));
                    minute = Int32.Parse(point.Substring(3, 2));
                }

                if (point.Length > 6)
                {
                    grad = Int32.Parse(point.Substring(1, 2));
                    minute = Int32.Parse(point.Substring(3, 2));

                    string sekString = point.Substring(5);
                    sekunde = Double.Parse(sekString.Substring(0, 2));

                    if (sekString.Length > 2)
                        sekunde += Double.Parse("0," + sekString.Substring(2));
                }

                InitByGrad(indicator, grad, minute, sekunde);
            }

            #endregion

            #region Private Helper
            private void InitByGrad(string indicator, int grad, int minute, double sekunde)
            {
                m_Indicator = indicator;

                if (indicator != "N" && indicator != "S" && indicator != "W" && indicator != "E")
                    throw new ArgumentException("LOC must be N,S,W or E");

                m_Decimal = grad + (minute / 60.0) + (sekunde / 3600.0);

                switch (indicator)
                {
                    case "S":
                    case "E":
                        m_Decimal *= -1.0;
                        break;
                }
            }
            #endregion

            #region Overriden Methods
            public override string ToString()
            {
                StringBuilder sb = new StringBuilder();

                sb.Append(m_Indicator + " ");
                sb.Append(Grad + "° ");
                sb.Append(Minute + "' ");
                sb.Append(Sekunde + "''");

                return sb.ToString();
            }
            #endregion
        }
    }

    public class calculation
    {
        /// <summary>
        /// Gets the distance between two points.
        /// </summary>
        /// <param name="latitude1">The latitude1.</param>
        /// <param name="longitude1">The longitude1.</param>
        /// <param name="latitude2">The latitude2.</param>
        /// <param name="longitude2">The longitude2.</param>
        /// <returns></returns>
        public static double GetDistanceBetweenTwoPoints(double latitude1, double longitude1, double latitude2, double longitude2)
        {
            double theta = longitude1 - longitude2;
            double distance = Math.Sin(ConvertDecimalDegreesToRadians(latitude1)) *
                              Math.Sin(ConvertDecimalDegreesToRadians(latitude2)) +
                              Math.Cos(ConvertDecimalDegreesToRadians(latitude1)) *
                              Math.Cos(ConvertDecimalDegreesToRadians(latitude2)) *
                              Math.Cos(ConvertDecimalDegreesToRadians(theta));

            distance = Math.Acos(distance);
            distance = ConvertRadiansToDecimalDegrees(distance);
            distance = distance * 60 * 1.1515;
            // convert to kilometers
            return distance * 1.609344;
        }

        /// <summary>
        /// Converts the decimal degrees to radians.
        /// </summary>
        /// <param name="degree">The degree.</param>
        /// <returns></returns>
        private static double ConvertDecimalDegreesToRadians(double degree)
        {
            return (degree * Math.PI / 180.0);
        }

        /// <summary>
        /// Converts the radians to decimal degrees.
        /// </summary>
        /// <param name="radian">The radian.</param>
        /// <returns></returns>
        private static double ConvertRadiansToDecimalDegrees(double radian)
        {
            return (radian / Math.PI * 180.0);
        }
    }


}
namespace rowa.registry
{
    public class regkey
    {
        public static bool addKey(string key, string value)
        {
            try
            {
                if (Microsoft.Win32.Registry.CurrentUser.GetValue(key) == null)
                {
                    Microsoft.Win32.Registry.CurrentUser.CreateSubKey(key);
                }
                Microsoft.Win32.Registry.CurrentUser.SetValue(key, value);
                return true;
            }
            catch
            {
                return false;
            }
        }
        public static string readKey(string key)
        {
            return Convert.ToString(Microsoft.Win32.Registry.CurrentUser.GetValue(key));
        }
    }
}


namespace rowa.ActiveDirectory
{
    using System.DirectoryServices;
    using System.DirectoryServices.ActiveDirectory;
    public class Domaincontroler
    {
            private System.Data.DataSet addata = null;
            /// <summary>
            /// liefert ein Dataset zurück, welches alle Informationen zu einem User beinhaltet
            /// </summary>
            /// 
            /// <returns>Dataset</returns>
            /// <remarks></remarks>
            /// 
            public System.Data.DataSet getADData(string username, string LDAP)
            {
                System.Data.DataSet ds = new System.Data.DataSet("result");
                System.Data.DataTable dt = ds.Tables.Add("item");
                dt.Columns.Add("sortOrder", System.Type.GetType("System.Int32"));
                dt.Columns.Add("preW2k", System.Type.GetType("System.String"));
                System.Data.DataRow dr = null;
                string strLDAP = "GC://" + LDAP ;

                System.DirectoryServices.DirectoryEntry m_obDirEntry = new System.DirectoryServices.DirectoryEntry(strLDAP);

                //m_obDirEntry.AuthenticationType = AuthenticationTypes.ReadonlyServer;

                System.DirectoryServices.DirectorySearcher srch = new System.DirectoryServices.DirectorySearcher(m_obDirEntry);
                System.DirectoryServices.SearchResultCollection results = null;
                srch.Filter = "samaccountname=" + username.Substring(username.IndexOf("\\") + 1);

                

                results = srch.FindAll();

                // assemble dataset
                foreach (System.DirectoryServices.SearchResult result in results)
                {
                    System.DirectoryServices.ResultPropertyCollection propColl = result.Properties;
                    // add new row to table
                    dr = dt.NewRow();
                    // check if column already exists
                    foreach (string strKey in propColl.PropertyNames)
                    {
                        bool alreadyExists = false;
                        foreach (System.Data.DataColumn col in dt.Columns)
                        {
                            if (col.ColumnName == strKey)
                            {
                                alreadyExists = true;
                            }
                        }
                        // if it does not exist, add it
                        if (alreadyExists == false)
                        {
                            dt.Columns.Add(strKey, System.Type.GetType("System.String"));
                        }

                        // add properties from AD object
                        foreach (object obProp in propColl[strKey])
                        {
                            if (strKey == "distinguishedname")
                            {
                                //If obProp.ToString.Contains(username.Substring(0, username.IndexOf("\"))) = True Then

                                //End If
                                dr["preW2k"] = getPreW2k(obProp.ToString(), propColl["samaccountname"][0].ToString());
                            }
                            dr[strKey] = obProp;
                        }
                    }
                    if (dr["preW2k"].ToString().ToLower() == username.ToLower())
                    {
                        dt.Rows.Add(dr);
                    }
                }
                addata = ds;
                return ds;
            }
            /// <summary>
            /// Hilfsfunktion für getADData
            /// </summary>
            /// <param name="dn"></param>
            /// <param name="samaccountname"></param>
            /// <returns></returns>
            /// <remarks></remarks>
            private string getPreW2k(string dn, string samaccountname)
            {
                string[] strWords = null;
                char[] strSeparators = { ',' };
                string domain = "";
                bool domainfound = false;
                strWords = dn.Split(strSeparators);
                int i = 0;
                for (i = 0; i <= strWords.Length; i++)
                {
                    if (strWords[i].StartsWith("DC="))
                    {
                        domain = strWords[i].Substring(3, strWords[i].Length - 3);
                        domainfound = true;
                    }
                    if (domainfound == true)
                    {
                        break; // TODO: might not be correct. Was : Exit For
                    }
                }
                return (domain + "\\" + samaccountname).ToUpper();
            }


            public string postalcode(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["postalcode"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string country(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["co"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string displayname(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["displayname"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string streetaddress(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["streetaddress"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string city(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["l"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string office(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["physicaldeliveryofficename"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string surename(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["sn"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string givenname(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["givenname"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string mail(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["mail"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string department(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["department"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string telephonenumber(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["telephonenumber"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string whenchangedpwdlastset(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["pwdlastset"].ToString();
                }
                catch
                {
                    return "";
                }
            }


            public string whencreated(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["whencreated"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string whenchanged(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["whenchanged"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string fax(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["facsimiletelephonenumber"].ToString();
                }
                catch
                {
                    return "";
                }
            }

            public string lastlogontimestamp(string username, string LDAP)
            {
                if (addata == null)
                {
                    getADData(username, LDAP);
                }
                try
                {
                    return addata.Tables["item"].Rows[0]["lastlogontimestamp"].ToString();
                }
                catch
                {
                    return "";
                }
            }


        }


    public class Account
    {
        /// <summary>
        /// Liefert den UserAccount vom SID in Form von Domain\UserName.
        /// </summary>
        /// <param name="SID">Der SecurityIdentifier</param>
        public static string GetLocalUserNamefromSID(System.Security.Principal.SecurityIdentifier SID)
        {
            System.Security.Principal.NTAccount NTUser = (System.Security.Principal.NTAccount)SID.Translate(typeof(System.Security.Principal.NTAccount));
            return NTUser.ToString();
        }

    }

    
    
    /// <summary>
    /// Achtung: Nur für eigene Domain nutzbar!
    /// </summary>
    public class member
    {

        /// <summary>
        ///     Ermittelt alle Gruppen die ein bestimmter User gehört.
        /// </summary>
        /// <param name="username">
        ///     Windows-NT-Anmeldename des Benutzers für welchen die Gruppenzugehörigkeit ermittelt werden soll
        /// </param>
        /// <returns>
        ///     eine Liste mit den Gruppennamen
        /// </returns>
        public static List<String> GetGroups(string username)
        {
            List<string> groups = new List<string>();
            // Objekt für AD-Abfrage erzeugen
            using (DirectorySearcher searcher = new DirectorySearcher(new DirectoryEntry(string.Empty)))
            {
                // nach Kriterium filtern - hier nach Gruppe mit einem best. Namen (Inhalt von 'username')
                searcher.Filter = string.Concat(string.Format(@"(&(ObjectClass=user)(sAMAccountName={0}))", username));

                // Anfrage mit gesetzteen Filter ausführen und Ergebnisse durch iterieren
                foreach (SearchResult result in searcher.FindAll())
                {
                    // Eigenschaft 'MemberOf' des AD-Knotenpunktes 'result' durch iterieren
                    foreach (var group in result.Properties["MemberOf"])
                    {
                        // cast von 'group' zum Datentyp 'string' sollte nicht möglich sein, wird 'groupResult' 'null'
                        string groupResult = group as string;

                        if (groupResult != null)
                        {
                            // CN aus dem Pfad extrahieren und zur Liste hinzufügen
                            groups.Add(groupResult.Substring(3, groupResult.IndexOf(',') - 3));
                        }
                    }
                }
            }
            return groups;
        }
    }
    public class group
    {
        /// <summary>
        ///     Ermittelt alle Benutzer die einer Gruppe angehören.
        /// </summary>
        /// <param name="group">
        ///     Name der Gruppe für welche alle zugehörigen Mitglieder ermittelt werden sollen.
        /// </param>
        /// <returns>
        ///     eine Liste mit den Mitgliedernamen
        /// </returns>
        private List<string> GetMember(string group)
        {
            List<string> members = new List<string>();
            // Objekt für AD-Abfrage erzeugen
            using (DirectorySearcher searcher = new DirectorySearcher(new DirectoryEntry(string.Empty)))
            {
                // nach Kriterium filtern - hier nach Gruppe mit einem best. Namen (Inhalt von 'group')
                searcher.Filter = string.Format(@"(&(objectClass=group)(cn={0}))", group);

                // Anfrage mit gesetzteen Filter ausführen und Ergebnisse durch iterieren
                foreach (SearchResult result in searcher.FindAll())
                {
                    // Eigenschaft 'member' des AD-Knotenpunktes 'result' durch iterieren
                    foreach (var member in result.Properties["member"])
                    {
                        // AD-Eintrag für Suchergebnis abrufen
                        using (DirectoryEntry memberResult = new DirectoryEntry(string.Format("LDAP://{0}", member)))
                        {
                            string username = null;

                            // wenn Fehler beim abrufen...
                            try
                            {
                                username = memberResult.Properties["sAMAccountName"].Value as string;
                            }
                            catch (Exception) //...dann von der Eigenschaft 'Path' die Erste CN nehmen
                            {
                                username = memberResult.Path.Substring(0, memberResult.Path.IndexOf(','))
                                                            .Replace("LDAP://CN=", string.Empty);
                            }

                            // wenn 'username' nicht 'null' dann zur Liste hinzufügen
                            if (username != null)
                                members.Add(username);
                        }
                    }
                }
            }
            return members;
        }

    }

}